"""What quantization buys: one panel per model, from fig2_data.json.

As in the study's figures.py (draw_front): bytes against the measured score,
both log; the whole model cast to one format as a line of hollow circles; the
allocation's measured front as filled dots; a ring on its cheapest passing
point; the pass limit dashed at 1. The method is drawn in series 6, a colour no test
function has in the κ figure, so the two linked figures never share a colour for different things. A log axis cannot reach zero, so scores
below the data's floor (score_floor_drawn_as_zero; in this data only exact
zeros) sit on a "0" row set apart from the log scale by an axis break;
non-finite scores on the top row. Format labels sit above-right of their
point, the lower of two points at the same size below-left, both on a halo.
"""
import math

from figlib import FONT, LogScale, Svg, bytes_label, decade, legend, variant

NAME = {"forrester": "Forrester, 1 input", "branin": "Branin, 2 inputs", "ishigami": "Ishigami, 3 inputs",
        "hartmann6": "Hartmann 6, 6 inputs", "borehole": "Borehole, 8 inputs"}
UNIFORM = {"f64": "float64", "f32": "float32", "bf16": "bfloat16", "f16": "float16", "e4m3": "float8"}


def title(c):
    prob = c["stem"].split("_n")[0]
    return f"{NAME.get(prob, prob)}, n = {c['n_train']}" + (" sparse" if c["kind"] == "sparse" else "")


def note(c):
    lp, best, sv = c["last_pass"], c["uniform_best_pass"], c["saving_vs_uniform"]
    svt = f"{sv:.3g}" if sv >= 1.1 else f"{sv:.4g}"
    rel = f"{svt}× smaller than " if sv >= 1.0005 else "the same size as "
    lp_bytes = float(f"{lp['bytes']:.3g}")
    return [f"last passing: {bytes_label(lp_bytes)},", rel + UNIFORM.get(best["format"], best["format"])]


ARTICLE = {"font": FONT, "small": 12, "note0": 31, "note_dy": 15, "left": 62, "ptop": 64, "pbot": (30, 46),
           "tick_dy": 17, "tick_y": 4.5, "lab": (6, -7, -7, 15)}
# The compact still for a card (compact()): every label at 14 px in a 320 px layout, so it renders at
# 13 px or more at 300 px and up, with wider gaps between labels.
COMPACT = {"font": 14, "small": 14, "note0": 38, "note_dy": 19, "left": 70, "ptop": 84, "pbot": (34, 56),
           "tick_dy": 21, "tick_y": 5, "lab": (8, -10, -9, 21)}


def panel(svg, c, ci, x, y, w, h, floor, topv, show_x_title, show_y_title, t=ARTICLE):
    """One model. Its marks carry data-c (the cell's row in fig2_data.json), data-s ("u" for a uniform
    cast, "f" for a front point) and data-j (the row in that list), for the interactive reading.
    `t` holds the type sizes and offsets: the article's, or the compact still's."""
    fs = t["font"]
    left, right, ptop, pbot = t["left"], 8, t["ptop"], t["pbot"][1] if show_x_title else t["pbot"][0]
    svg.add(f'<g class="fig-panel" data-c="{ci}">')
    svg.text(x, y + fs + 1, title(c), cls="fig-strong", size=fs)
    for k, line in enumerate(note(c)):
        svg.text(x, y + t["note0"] + k * t["note_dy"], line, cls="fig-note", size=t["small"], extra=f' data-line="{k}"')
    allb = [p["bytes"] for p in c["uniform"] + c["front"]]
    X = LogScale(min(allb) / 1.6, max(allb) * 1.35, x + left, x + w - right)
    base = y + h - pbot
    zero_y = base - 6
    Y = LogScale(floor, topv * 3, base - 24, y + ptop + 8)

    def py_of(sc):
        if not math.isfinite(sc):
            return Y(topv)
        return zero_y if sc < floor or sc == 0 else Y(sc)
    # grid and ticks
    for e in (-3, 0, 3, 6, 9, 12):
        v = 10.0 ** e
        if floor < v < topv * 3:
            svg.line(x + left, Y(v), x + w - right, Y(v), "fig-grid")
            svg.text(x + left - 6, Y(v) + t["tick_y"], "1" if e == 0 else decade(e), "end", size=fs)
    svg.text(x + left - 6, zero_y + t["tick_y"], "0", "end", size=fs)
    lo, hi = math.ceil(math.log10(min(allb) / 1.6)), math.floor(math.log10(max(allb) * 1.35))
    for e in range(lo, hi + 1):
        gx = X(10 ** e)
        svg.line(gx, Y(topv * 3), gx, base, "fig-grid")
        svg.text(gx, base + t["tick_dy"], bytes_label(10 ** e), "middle", size=fs)
    svg.line(x + left, y + h - pbot, x + w - right, y + h - pbot, "fig-axis")
    # the y axis, broken between the log scale and the 0 row
    xl = x + left
    svg.line(xl, Y(topv * 3), xl, base - 18, "fig-axis")
    svg.line(xl, base - 12, xl, base, "fig-axis")
    for by in (base - 18, base - 12):
        svg.line(xl - 4, by + 2, xl + 4, by - 2, "fig-axis")
    if show_x_title:
        svg.text(x + left + (w - left - right) / 2, y + h - 6, "bytes stored", "middle", size=fs)
    if show_y_title:
        cy = (Y(topv * 3) + y + h - pbot) / 2
        svg.add(f'<text x="0" y="0" text-anchor="middle" font-size="{fs}" transform="translate({x + fs - 1:.1f} {cy:.1f}) '
                f'rotate(-90)">worst test, 0 = no change</text>')
    svg.line(x + left, Y(1), x + w - right, Y(1), "fig-limit", ' stroke-width="1.1"')
    ub = c["uniform"]
    svg.polyline([(X(p["bytes"]), py_of(p["score"])) for p in ub], "fig-line-muted", ' stroke-width="1.1"')
    for j, p in enumerate(ub):
        px, py = X(p["bytes"]), py_of(p["score"])
        svg.circle(px, py, 3.8, "fig-pt fig-mark-ink fig-hollow", f' stroke-width="1.3" data-c="{ci}" data-s="u" data-j="{j}"')
        same = [q for q in ub if q["bytes"] == p["bytes"]]
        upper = len(same) == 1 or p["score"] >= max(q["score"] for q in same)
        label = UNIFORM.get(p["format"], p["format"])
        if p["format"] != "f64":   # float64 is the line's right end; its label would sit on the front
            ax, ay, bx, by_ = t["lab"]
            if upper:
                svg.text(px + ax, py + ay, label, cls="fig-label", size=fs)
            else:   # the line runs up-left and down-right from here: below-left is clear
                svg.text(px + bx, py + by_, label, "end", cls="fig-label", size=fs)
    for j, p in enumerate(c["front"]):
        svg.circle(X(p["bytes"]), py_of(p["score"]), 3.0, "fig-pt fig-series-6", f' data-c="{ci}" data-s="f" data-j="{j}"')
    lp = c["last_pass"]
    lps = next((p["score"] for p in c["front"] if p["bytes"] == lp["bytes"]), None)
    if lps is not None:
        svg.circle(X(lp["bytes"]), py_of(lps), 7.5, "fig-line-6 fig-last", ' stroke-width="1.6"')
    svg.add("</g>")


def draw(data, width):
    d = data["fig2_data.json"]
    cells, floor, topv = d["cells"], d["score_floor_drawn_as_zero"], d["score_top_drawn_as_infinite"]
    cols = {"s": 1, "m": 2, "l": 3}[variant(width)]
    ph = {"s": 280, "m": 280, "l": 270}[variant(width)]
    svg = Svg(width)
    y = legend(svg, [
        (lambda s, x, yy: (s.line(x - 8, yy, x + 8, yy, "fig-line-muted", ' stroke-width="1.1"'),
                           s.circle(x, yy, 3.8, "fig-mark-ink fig-hollow", ' stroke-width="1.3"')),
         "every part at one format"),
        (lambda s, x, yy: s.circle(x, yy, 3.0, "fig-series-6"), "per-part allocation"),
        (lambda s, x, yy: s.circle(x, yy, 6.5, "fig-line-6", ' stroke-width="1.6"'), "its last passing point"),
        (lambda s, x, yy: s.line(x - 8, yy, x + 8, yy, "fig-limit", ' stroke-width="1.1"'), "pass limit"),
    ], 6, 16, width - 6) + 14
    gap = 18
    pw = (width - gap * (cols - 1)) / cols
    rows = math.ceil(len(cells) / cols)
    for i, c in enumerate(cells):
        r, k = divmod(i, cols)
        last_row = r == rows - 1 or (cols == 1)
        panel(svg, c, i, k * (pw + gap), y + r * (ph + 14), pw, ph, floor, topv, last_row, k == 0)
    return svg.svg(y + rows * (ph + 14), variant(width))


def describe(data):
    out = []
    for c in data["fig2_data.json"]["cells"]:
        lp, best = c["last_pass"], c["uniform_best_pass"]
        sv, bf = c["saving_vs_uniform"], UNIFORM.get(best["format"], best["format"])
        rel = (f"{sv:.3g} times smaller than the best single format ({bf})" if sv >= 1.005
               else f"the same size as the best single format ({bf}) to within 1%")
        out.append(f"{title(c)}: the cheapest passing allocation stores {bytes_label(lp['bytes'])}, {rel}.")
    return "Six panels, one per model. " + " ".join(out)



def compact(data):
    """One panel (Hartmann 6, n = 1024, the model where one format for every part passes and the
    method matches it) as a still for a card: 320 px wide, the legend, both axis titles and the
    panel's two "last passing" lines, every label at 14 px."""
    d = data["fig2_data.json"]
    cells, floor, topv = d["cells"], d["score_floor_drawn_as_zero"], d["score_top_drawn_as_infinite"]
    ci = next(i for i, c in enumerate(cells) if c["stem"] == "hartmann6_n1024_s7_dense")
    width = 320
    svg = Svg(width)
    y = legend(svg, [
        (lambda s, x, yy: (s.line(x - 8, yy, x + 8, yy, "fig-line-muted", ' stroke-width="1.1"'),
                           s.circle(x, yy, 4.2, "fig-mark-ink fig-hollow", ' stroke-width="1.3"')),
         "every part at one format"),
        (lambda s, x, yy: s.circle(x, yy, 3.4, "fig-series-6"), "per-part allocation"),
        (lambda s, x, yy: s.circle(x, yy, 7, "fig-line-6", ' stroke-width="1.6"'), "its last passing point"),
        (lambda s, x, yy: s.line(x - 8, yy, x + 8, yy, "fig-limit", ' stroke-width="1.1"'), "pass limit"),
    ], 0, 18, width, size=14) + 22
    h = 330
    panel(svg, cells[ci], ci, 0, y, width, h, floor, topv, True, True, COMPACT)
    return svg.svg(y + h + 4, "s")
