"""Plan the spacing and apply it to the glyphs (design document,
section 4.5)."""

from collections import defaultdict
from dataclasses import dataclass, replace

from charstring import transformed
from outline import moved
from plan.metrics import tfm_char, units
from plan.spacing import fit as fitting
from plan.spacing.ink import Gaps

DIGITS = range(48, 58)


@dataclass(frozen=True)
class Report:
    """What the build's tables record about the spacing."""

    rows: tuple         # (glyph, change of advance, move of outline)
    systems: tuple      # (role, fitted slots, RMS before, RMS after)
    weights: tuple      # (role, pair, weight) of the differential rule
    c: dict             # delimiter context -> change of its side bearing
    shift: int
    floor_widening: tuple   # (code point, size, units)


def plan_spacing(design, sources, glyphs, optical, codepoint_glyph):
    """Return the glyphs with the spacing applied, and a Report.

    glyphs: the plan's glyphs in order; optical: text glyph name ->
    (script, scriptscript) names; codepoint_glyph: code point -> name.
    """
    rules = design.spacing
    by_name = {glyph.name: glyph for glyph in glyphs}
    by_origin = defaultdict(list)
    for glyph in glyphs:
        if glyph.origin:
            by_origin[glyph.origin].append(glyph)
    gaps = Gaps()
    sources_used = {source for source, _ in by_origin}
    roles = [design.roles[r] for r in rules.systems
             if design.roles[r].text in sources_used]
    present = {role.name for role in roles}

    def kern_of(left, right):
        """The TFM kern between two glyphs of one source, in units."""
        if not (left.origin and right.origin) or \
                left.origin[0] != right.origin[0]:
            return 0
        source = left.origin[0]
        role = design.role_of(source)
        char = tfm_char(design, sources, source, left.origin[1])
        if right.origin[1] == sources.package.skewchar(source):
            return 0
        return units(char.kerns.get(right.origin[1], 0) * role.scale)

    def text_glyph(role, slot):
        """The glyph of a slot of the role's text font; an encoded one
        if there is one."""
        found = sorted(by_origin.get((role.text, slot), ()),
                       key=lambda glyph: not glyph.codepoints)
        return found[0] if found else None

    delimiter = {name: by_name[codepoint_glyph[getattr(rules, group)[0]]]
                 for name, group, _ in fitting.CONTEXTS}

    def make_fit(role, slots):
        def kern(a, b):
            return kern_of(text_glyph(role, a), text_glyph(role, b))
        context_gaps = {}
        for name, _, side in fitting.CONTEXTS:
            d = delimiter[name]
            row = {}
            for s in slots:
                g = text_glyph(role, s)
                pair = (d, g) if side == "l" else (g, d)
                row[s] = gaps.gap(*pair, kern=kern_of(*pair))
            context_gaps[name] = row
        return fitting.Fit(slots, kern, context_gaps, rules.floor)

    # 1. Latin letters of each Latin role: r and l, and c from the
    # first.
    letters = [ord(ch) for ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
               "abcdefghijklmnopqrstuvwxyz"]
    values, weights = {}, []
    c = None
    latin_roles = [design.roles[r] for r in rules.latin if r in present]
    for role in latin_roles:
        fit = make_fit(role, letters)
        result, c_found, chosen = fitting.latin(fit, rules, c)
        if c is None:
            c = c_found
        values[role.name] = result
        weights += [(role.name, pair, w) for pair, w in chosen.items()]
    # 2. The other glyphs of every kern system.
    summaries = []
    for role in roles:
        fixed = values.get(role.name, {})
        slots = sorted(set(fixed) | set(_system_slots(
            role, design, sources, text_glyph, kern_of,
            rules.excluded_slots)))
        fit = make_fit(role, slots)
        has_latin = role.name in values
        rest, _ = fitting.solve(
            fit, fixed=fixed, c=c if has_latin else _zero(),
            alpha=rules.alpha if has_latin else 0, gauge=not fixed,
            blocks=[tuple(DIGITS)])
        values[role.name] = {**fixed, **rest}
        before = [fit.kern(a, b) for a in slots for b in slots]
        after = fitting.errors(fit, values[role.name]).values()
        summaries.append((role.name, len(slots), _rms(before), _rms(after)))
    # 3. The common move of the outlines, set by the upright d.
    first = latin_roles[0].name
    shift = fitting.shift(rules, values[first])
    for name in rules.shifted:
        role_values = values.get(name, {})
        for s, (r, l) in role_values.items():
            role_values[s] = (r - shift, l + shift)
    c = {name: v - shift if name in fitting.OPENING else v + shift
         for name, v in c.items()}

    changes = {}        # glyph name -> (change of advance, move)

    def change(glyph, advance, move):
        old = changes.get(glyph.name, (0, 0))
        changes[glyph.name] = (old[0] + advance, old[1] + move)

    for role in roles:
        for s, (r, l) in values[role.name].items():
            for source in (role.text, role.script, role.scriptscript):
                for glyph in by_origin.get((source, s), ()):
                    change(glyph, r + l, l)
    # 4. The delimiters' side bearings, on their copies and sizes.
    for name, group, side in fitting.CONTEXTS:
        for codepoint in getattr(rules, group):
            for glyph in _family(design, by_name,
                                 codepoint_glyph[codepoint]):
                change(glyph, c[name], c[name] if side == "r" else 0)
    updated = _apply(glyphs, changes)
    # 5. The opening floor and ceiling, wide enough for f j y p.
    new = {glyph.name: glyph for glyph in updated}
    widening = []
    base = [codepoint_glyph[cp] for cp in rules.floor_brackets]
    letter_names = [text_glyph(latin_roles[0], ord(ch)).name
                    for ch in rules.floor_letters]
    for size in range(3):
        def sized(name):
            return name if size == 0 else optical[name][size - 1]
        bracket = sized(base[0])
        needs = []
        for name in letter_names:
            old, now = by_name[sized(name)], new[sized(name)]
            original = gaps.gap(by_name[bracket], old)
            needs.append(min(rules.floor, original)
                         - gaps.gap(new[bracket], now))
        amount = fitting.floor_widening(needs)
        for name in base:
            widening.append((by_name[name].codepoints[0], size, amount))
            change(by_name[sized(name)], amount, 0)
    updated = _apply(glyphs, changes)
    rows = tuple((name,) + changes[name] for name in
                 [g.name for g in glyphs if g.name in changes])
    return updated, Report(rows, tuple(summaries), tuple(weights), c,
                           shift, tuple(widening))


def _zero():
    return {name: 0 for name, _, _ in fitting.CONTEXTS}


def _rms(values):
    values = list(values)
    return (sum(v * v for v in values) / len(values)) ** 0.5


def _system_slots(role, design, sources, text_glyph, kern_of, excluded):
    """Slots of the text font with a kern to or from another slot of
    the font, both with glyphs (the kerns of section 4.4)."""
    slots = set()
    for a in sources.metrics[role.text].chars:
        left = text_glyph(role, a)
        if left is None:
            continue
        for b in tfm_char(design, sources, role.text, a).kerns:
            right = text_glyph(role, b)
            if right is not None and kern_of(left, right):
                slots.update((a, b))
    return sorted(slots - set(excluded))


def _family(design, by_name, name):
    """A glyph and the glyphs reached from it that keep its slot's box
    in one of its role's sizes: its script and scriptscript forms and
    its alternates (named after it, section 11.2).  Stages scaled from
    it have no origin and are left alone (section 4.5.5)."""
    root = by_name[name]
    role = design.role_of(root.origin[0])
    sizes = {role.text, role.script, role.scriptscript}
    return [glyph for glyph in by_name.values()
            if (glyph.name == name or glyph.name.startswith(name + "."))
            and glyph.origin
            and glyph.origin[0] in sizes
            and glyph.origin[1] == root.origin[1]]


def _apply(glyphs, changes):
    """Glyphs with their advance and outline changed; the hints, the
    accent attachment and the MathKern follow (sections 4.3, 4.5.7)."""
    result = []
    for glyph in glyphs:
        if glyph.name not in changes:
            result.append(glyph)
            continue
        advance, dx = changes[glyph.name]
        rho, lam = advance - dx, dx
        kerns = dict(glyph.math_kern or {})
        for corner, value in (("TopRight", -rho), ("BottomRight", -rho),
                              ("TopLeft", -lam), ("BottomLeft", -lam)):
            kerns[corner] = kerns.get(corner, 0) + value
        kerns = {k: v for k, v in kerns.items() if v}
        result.append(replace(
            glyph,
            advance=glyph.advance + advance,
            outline=moved(glyph.outline, dx, 0),
            program=None if glyph.program is None
            else transformed(glyph.program, 1, dx, 0),
            top_accent=None if glyph.top_accent is None
            else glyph.top_accent + dx,
            math_kern=kerns or None))
    return tuple(result)
