"""The fits of section 4.5: Latin letters, then the other glyphs of
each kern system.  Values are in font units and rounded at the end
(ties to even, as in section 4.1)."""

import math

import numpy as np

from plan.spacing.solve import least_squares

# The six contexts of a delimiter and a letter: which delimiter, and
# whether the letter's left (l) or right (r) side faces it.
CONTEXTS = (("(x", "paren_open", "l"), ("[x", "bracket_open", "l"),
            ("|x", "bar", "l"), ("x)", "paren_close", "r"),
            ("x]", "bracket_close", "r"), ("x|", "bar", "r"))
OPENING = ("(x", "[x", "|x")


class Fit:
    """Inputs of one kern system.

    slots: the fitted slots, in order; kern(a, b): the kern in font
    units; gaps[context][slot]: the ink gap next to the delimiter in
    the original (None where the glyphs share no line of ink)."""

    def __init__(self, slots, kern, gaps, floor):
        self.slots = tuple(slots)
        self.kern = kern
        self.gaps = gaps
        self.floor = floor


def _rows(fit, fixed, c, alpha, weights, c_free):
    """Least-squares rows over the unknowns [r, l of the free slots,
    then c if free]; returns A, b, w and the free slots."""
    free = [s for s in fit.slots if s not in fixed]
    k = {s: i for i, s in enumerate(free)}
    n = len(free)
    size = 2 * n + (len(CONTEXTS) if c_free else 0)
    rows, b, w = [], [], []
    for a in fit.slots:
        for t in fit.slots:
            if a in fixed and t in fixed:
                continue
            row = np.zeros(size)
            target = fit.kern(a, t)
            if a in fixed:
                target -= fixed[a][0]
            else:
                row[k[a]] = 1
            if t in fixed:
                target -= fixed[t][1]
            else:
                row[n + k[t]] += 1
            rows.append(row)
            b.append(target)
            w.append(weights.get((a, t), 1))
    if alpha:
        for j, (name, _, side) in enumerate(CONTEXTS):
            for s in free:
                row = np.zeros(size)
                row[k[s] if side == "r" else n + k[s]] = 1
                target = 0
                if c_free:
                    row[2 * n + j] = 1
                else:
                    target = -c[name]
                rows.append(row)
                b.append(target)
                w.append(alpha)
    return np.array(rows), np.array(b, float), np.array(w, float), free


def _floors(fit, free, c, c_free, size):
    """Rows of G x >= h: the ink gap next to a delimiter stays at least
    min(floor, original)."""
    G, h = [], []
    n = len(free)
    for j, (name, _, side) in enumerate(CONTEXTS):
        for i, s in enumerate(free):
            original = fit.gaps[name].get(s)
            if original is None:
                continue
            row = np.zeros(size)
            row[i if side == "r" else n + i] = 1
            bound = min(fit.floor, original) - original
            if c_free:
                row[2 * n + j] = 1
            else:
                bound -= c[name]
            G.append(row)
            h.append(bound)
    return np.array(G).reshape(-1, size), np.array(h, float)


def solve(fit, fixed=None, c=None, alpha=1, weights=None, gauge=False,
          blocks=()):
    """r and l of every free slot (and c if c is None), rounded.

    gauge: add sum(r) = sum(l) over the free slots.  blocks: groups of
    slots that move as one, with r = -l (the digits)."""
    fixed = fixed or {}
    weights = weights or {}
    c_free = c is None
    A, b, w, free = _rows(fit, fixed, c, alpha, weights, c_free)
    size = A.shape[1]
    n = len(free)
    G, h = _floors(fit, free, c, c_free, size)
    E, e = [], []
    if gauge:
        row = np.zeros(size)
        row[:n], row[n:2 * n] = 1, -1
        E.append(row)
        e.append(0)
    index = {s: i for i, s in enumerate(free)}
    for block in blocks:
        members = [index[s] for s in block if s in index]
        if not members:
            continue
        first = members[0]
        for i in members[1:]:
            for offset in (0, n):
                row = np.zeros(size)
                row[offset + i], row[offset + first] = 1, -1
                E.append(row)
                e.append(0)
        row = np.zeros(size)
        row[first], row[n + first] = 1, 1
        E.append(row)
        e.append(0)
    x = least_squares(A, b, w, np.array(E).reshape(-1, size),
                      np.array(e, float), G, h)
    x = np.rint(x)
    values = {s: (int(x[i]), int(x[n + i])) for i, s in enumerate(free)}
    if c_free:
        c = {name: int(x[2 * n + j])
             for j, (name, _, _) in enumerate(CONTEXTS)}
    return values, c


def errors(fit, values):
    """slot pair -> r(a) + l(b) - kern(a, b), over the fitted slots."""
    return {(a, t): values[a][0] + values[t][1] - fit.kern(a, t)
            for a in fit.slots for t in fit.slots}


def latin(fit, rules, c=None):
    """The Latin letters of a system (sections 4.5.2 and 4.5.3).

    With c None, the delimiters' c are found too and the gauge is
    sum(r) = sum(l); otherwise c is given and fixes the gauge.  The
    differential pairs get the least common weight that brings them
    within the threshold (section 4.5.2)."""
    gauge = c is None
    d = ord(rules.differential)
    wanted = [ord(v) for v in rules.variables]
    first, _ = solve(fit, c=c, alpha=rules.alpha, gauge=gauge)
    e0 = errors(fit, first)
    chosen = {}
    while True:
        selected = [v for v in wanted if abs(e0[d, v]) > rules.threshold]
        if not selected:
            break
        for weight in rules.weights:
            trial = {(d, v): weight for v in selected}
            values, _ = solve(fit, c=c, alpha=rules.alpha, weights=trial,
                              gauge=gauge)
            e = errors(fit, values)
            if all(abs(e[d, v]) <= rules.threshold for v in wanted):
                chosen = trial
                break
        if chosen:
            break
        wanted.remove(max(wanted, key=lambda v: abs(e0[d, v])))
    values, c = solve(fit, c=c, alpha=rules.alpha, weights=chosen,
                      gauge=gauge)
    return values, c, chosen


def shift(rules, latin_values):
    """The common move of the outlines (section 4.5.2), set by the
    upright d before the integration variables, weighted by their
    frequency."""
    pairs = [(ord(v), weight) for v, weight in rules.shift_pairs]
    total = sum(weight for _, weight in pairs)
    value = -sum(weight * latin_values[s][1] for s, weight in pairs) / total
    return int(np.rint(value))


def floor_widening(needs):
    """The least whole number of units that meets every need."""
    return max(0, math.ceil(max(needs)))
