"""What gets quantized along the front: bytes per group at passing front points, from fig3_data.json.

As in the study's figures.py (fig_composition): one bar per point, all float64
at the top and the cheapest passing point at the bottom, split into the factor,
the weights, the inputs, and the hyperparameters with the transforms; every
group's format listed under the bar (no text is set on a coloured segment, so
any palette reads).
"""
from figlib import LinScale, Svg, bytes_label, 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"}
SEGMENTS = [("factor", ["factor"], "uncertainty factor", "fig-area-a"),
            ("alpha", ["alpha"], "weights", "fig-area-b"),
            ("inputs", ["inputs"], "inputs", "fig-series-3"),
            ("small", ["hyper", "output", "input"], "hyperparameters and transforms", "fig-mark-muted")]
GROUP = {"hyper": "hyperparameters", "inputs": "inputs", "alpha": "weights"}


def fmt(a):
    f, mode = a.split("/")
    return UNIFORM.get(f, f) + (" (recomputed)" if mode == "consistent" else "")


def formats(b):
    a = b["assignment"]
    tr = "/".join(sorted({fmt(a[g]) for g in ("output", "input") if g in a}))
    return [f"uncertainty factor {fmt(a['factor'])}",
            ", ".join(f"{GROUP[g]} {fmt(a[g])}" for g in ("alpha", "inputs") if g in a),
            ", ".join(([f"hyperparameters {fmt(a['hyper'])}"] if "hyper" in a else []) + ([f"transforms {tr}"] if tr else []))]


def bar_label(j, nb):
    return "all float64" if j == 0 else ("last passing" if j == nb - 1 else f"front point {j + 1}")


def draw(data, width):
    """Each bar: its label (left at wide layouts, above it otherwise), the bar, and every group's format under it."""
    panels = data["fig3_data.json"]["panels"]
    v = variant(width)
    wide = v != "s"
    svg = Svg(width)
    swatch = lambda cls: (lambda s, x, y: s.rect(x - 6, y - 6, 12, 12, cls))  # noqa: E731
    y = legend(svg, [(swatch(cls), label) for _, _, label, cls in SEGMENTS], 6, 16, width - 6) + 16
    label_w = 104 if wide else 0
    bar_h = 20
    for pn in panels:
        prob, n = pn["stem"].split("_n")[0], int(pn["stem"].split("_n")[1].split("_")[0])
        svg.text(0, y + 13, f"{NAME.get(prob, prob)}, n = {n}", cls="fig-strong")
        y += 26
        bars = pn["bars"]
        xmax = max(b["bytes"] for b in bars)
        X = LinScale(0, xmax * 1.02, label_w, width - 8)
        per = bar_h + (0 if wide else 17) + 3 * 14 + 16
        base = y + len(bars) * per - 8
        step = 1e6 if xmax > 2e6 else (5e5 if xmax > 1e6 else 1e5)
        t = 0.0
        while t <= xmax * 1.02:
            svg.line(X(t), y - 4, X(t), base, "fig-grid")
            svg.text(X(t), base + 16, "0" if t == 0 else bytes_label(t), "start" if t == 0 and not wide else "middle", size=12)
            t += step
        svg.line(label_w, base, X(xmax * 1.02), base, "fig-axis")
        for j, b in enumerate(bars):
            if wide:
                svg.text(label_w - 8, y + bar_h / 2 + 4.5, bar_label(j, len(bars)), "end")
            else:
                svg.text(0, y + 12, bar_label(j, len(bars)), cls="fig-strong")
                y += 17
            x = 0
            for key, groups, _, cls in SEGMENTS:
                w = b["segments"][key]
                svg.rect(X(x), y, X(x + w) - X(x), bar_h, cls)
                x += w
            for k, t in enumerate(formats(b)):
                svg.text(label_w, y + bar_h + 14 + k * 14, t, size=12)
            y += bar_h + 3 * 14 + 16
        y = base + 34
    svg.text(label_w + (width - 8 - label_w) / 2, y - 6, "bytes stored", "middle")
    return svg.svg(y + 4, v)


def describe(data):
    out = []
    for pn in data["fig3_data.json"]["panels"]:
        prob = pn["stem"].split("_n")[0]
        steps = " → ".join(UNIFORM.get(b["assignment"]["factor"].split("/")[0], "?") for b in pn["bars"])
        out.append(f"{NAME.get(prob, prob)}: {len(pn['bars'])} passing points from {bytes_label(pn['bars'][0]['bytes'])} "
                   f"to {bytes_label(pn['bars'][-1]['bytes'])}; the factor's format along them: {steps}.")
    return "Horizontal bars of bytes per group, two models. " + " ".join(out)
