"""Rebuild the result card, the social card and the three figures of the khatraTTS post.

usage: uv run --with playwright python make_figures.py DATA_JSON FONT_DIR OUT_DIR
  DATA_JSON  khatratts-data.json (next to this script)
  FONT_DIR   folder holding cmu-serif-400.woff2 and cmu-serif-700.woff2 (the site's body face)
  OUT_DIR    where the JPEGs go

Every plotted value is read from DATA_JSON. The parameter counts in fig-sizes are the ones quoted in the post.
Pages are drawn as HTML and photographed with headless Chromium at 1600 px wide (1200 for the social card).
"""
import html
import json
import sys
from pathlib import Path

from playwright.sync_api import sync_playwright

PAPER, INK, CRIMSON, GREY, PALE, TINT, RULE = "#F7F6F3", "#111111", "#DC143C", "#5E5A57", "#F6D3DA", "#FCEBEE", "#D8D4CF"
PASS = 0.15
# parameter counts quoted in the post (17-language checkpoint; sanoTTS README)
SIZES = [("khatraTTS FlowLM (teacher)", 324_236_353, True), ("khatraTTS codec", 20_054_337, True),
         ("sanoTTS heart", 2_270_000, False), ("sanoTTS heart-nano", 294_279, False)]


def f3(x):
    return f"{x:.3f}".lstrip("0") if x < 1 else f"{x:.3f}"


def tiers(rows):
    """Language -> tier, straight from the per-sentence values."""
    out = {}
    for lang in sorted({r["language"] for r in rows}):
        rs = [r for r in rows if r["language"] == lang]
        n = sum(r["passed"] for r in rs)
        if n == 2:
            out[lang] = "mid" if all(r["cer_median_seed"] <= PASS for r in rs) else "best"
        else:
            out[lang] = "one" if n == 1 else "none"
    return out


def page(w, h, body, font_dir):
    return f"""<!doctype html><html><head><meta charset="utf-8">
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
@font-face {{ font-family: "CMU Serif"; font-weight: 400; src: url("file://{font_dir}/cmu-serif-400.woff2"); }}
@font-face {{ font-family: "CMU Serif"; font-weight: 700; src: url("file://{font_dir}/cmu-serif-700.woff2"); }}
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{ width: {w}px; height: {h}px; position: relative; overflow: hidden; background-color: {PAPER}; color: {INK};
  background-image: linear-gradient(#ECEAE6 1px, transparent 1px), linear-gradient(90deg, #ECEAE6 1px, transparent 1px);
  background-size: 20px 20px; font-family: "CMU Serif", serif; }}
.fr {{ position: absolute; background: {RULE}; }}
.px {{ font-family: "Press Start 2P", monospace; }}
.mono {{ font-family: "IBM Plex Mono", monospace; }}
.lab {{ position: absolute; left: 96px; top: 76px; font: 18px "Press Start 2P"; color: {GREY}; letter-spacing: 2px; }}
.mark {{ position: absolute; right: 96px; top: 56px; width: 75px; height: 75px; }}
.mark i {{ position: absolute; width: 25px; height: 25px; background: {CRIMSON}; }}
h1 {{ position: absolute; left: 96px; top: 136px; font: 44px "Press Start 2P"; letter-spacing: 2px; }}
.dash {{ position: absolute; left: 96px; top: 204px; width: 1230px; border-top: 5px dashed {CRIMSON}; }}
.sub {{ position: absolute; left: 96px; top: 234px; font: 22px "IBM Plex Mono"; color: {GREY}; }}
.src {{ position: absolute; left: 96px; bottom: 56px; font: 17px "IBM Plex Mono"; color: {GREY}; }}
.sq {{ display: inline-block; width: 44px; height: 44px; margin-right: 8px; border: 3px solid {INK}; vertical-align: middle; }}
.sq.mid {{ background: {CRIMSON}; border-color: {CRIMSON}; }}
.sq.best {{ background: {PALE}; border-color: {CRIMSON}; }}
.sq.one {{ background: repeating-linear-gradient(45deg, {GREY} 0 4px, {PAPER} 4px 10px); border-color: {GREY}; }}
.sq.none {{ background: {PAPER}; }}
.sq.nt {{ background: {PAPER}; border: 3px dashed #B5B0AA; }}
text {{ font-family: "IBM Plex Mono", monospace; }}
text.s {{ font-family: "CMU Serif", serif; }}
</style></head><body>
<div class="fr" style="left:58px;right:58px;top:34px;height:6px"></div><div class="fr" style="left:58px;right:58px;bottom:34px;height:6px"></div>
<div class="fr" style="left:34px;top:58px;bottom:58px;width:6px"></div><div class="fr" style="right:34px;top:58px;bottom:58px;width:6px"></div>
<div class="lab">AMPIXA LABS</div>
<div class="mark"><i style="left:25px;top:0"></i><i style="left:0;top:25px"></i><i style="left:50px;top:25px"></i><i style="left:25px;top:50px"></i></div>
{body}</body></html>"""


def head(title, sub):
    return f'<h1>{title}</h1><div class="dash"></div><div class="sub">{html.escape(sub)}</div>'


def squares(t, order=("mid", "best", "one", "none")):
    """Row of squares for the cards: languages that pass both sentences share one colour."""
    return "".join(f'<span class="sq {"mid" if k == "best" else k}"></span>' for k in order for _ in [l for l in t if t[l] == k])


def fig_cer(rows, t):
    rank = {"mid": 0, "best": 1, "one": 2, "none": 3}
    langs = sorted(t, key=lambda l: (rank[t[l]], max(r["cer_best"] for r in rows if r["language"] == l)))
    x0, x1, top, rh = 330, 1300, 330, 27
    X = lambda v: x0 + (x1 - x0) * v / 0.9
    n = len(langs) * 2
    bottom = top + n * rh + (len(langs) - 1) * 8
    s = [f'<rect x="{X(0)}" y="{top - 14}" width="{X(PASS) - X(0)}" height="{bottom - top + 20}" fill="{PALE}"/>']
    for v in (0, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9):
        s.append(f'<line x1="{X(v)}" x2="{X(v)}" y1="{top - 14}" y2="{bottom + 6}" stroke="{RULE}" stroke-width="2"/>')
        s.append(f'<text x="{X(v)}" y="{bottom + 34}" text-anchor="middle" font-size="18" fill="{GREY}">{f3(v) if v else "0"}</text>')
    s.append(f'<text x="{X(0.075)}" y="{top - 26}" text-anchor="middle" font-size="17" fill="{CRIMSON}">pass</text>')
    y = top
    for lang in langs:
        s.append(f'<text class="s" x="96" y="{y + rh + 2}" font-size="26">{lang}</text>')
        for r in sorted((r for r in rows if r["language"] == lang), key=lambda r: r["sentence"]):
            cy = y + rh / 2
            s.append(f'<text x="{x0 - 26}" y="{cy + 6}" text-anchor="end" font-size="17" fill="{GREY}">{r["sentence"]}</text>')
            s.append(f'<line x1="{X(0)}" x2="{X(0.9)}" y1="{cy}" y2="{cy}" stroke="{RULE}" stroke-width="1"/>')
            seeds = sorted(r["cer_all_seeds"].values())
            for v in seeds[1:]:
                s.append(f'<circle cx="{X(v):.1f}" cy="{cy}" r="7" fill="{GREY}" fill-opacity=".55"/>')
            b = seeds[0]
            assert b == r["cer_best"]
            if r["passed"]:
                s.append(f'<circle cx="{X(b):.1f}" cy="{cy}" r="9" fill="{CRIMSON}"/>')
            else:
                s.append(f'<circle cx="{X(b):.1f}" cy="{cy}" r="8" fill="{PAPER}" stroke="{INK}" stroke-width="3"/>')
            s.append(f'<text x="{x1 + 40}" y="{cy + 6}" font-size="18" font-weight="{600 if r["passed"] else 400}" '
                     f'fill="{CRIMSON if r["passed"] else INK}">{f3(b)}{"" if r["passed"] else "  fails"}</text>')
            y += rh
        y += 8
    h = bottom + 150
    leg = (f'<svg width="1600" height="{h}" style="position:absolute;left:0;top:0">{"".join(s)}'
           f'<text x="{X(0.45)}" y="{bottom + 66}" text-anchor="middle" font-size="18" fill="{GREY}">character error rate (MMS-1b-all), lower is better</text>'
           f'<text x="{x1 + 40}" y="{top - 26}" font-size="17" fill="{GREY}">best of 3</text></svg>')
    npass = sum(r["passed"] for r in rows)
    body = head("WHICH SENTENCES PASS", f"two test sentences (A, B) per language, three samples each · best sample in crimson · {npass} of {len(rows)} pass") + leg
    return 1600, h, body


def fig_coverage(rows, t, not_tested):
    groups = [("mid", "Both sentences pass, on the middle sample too"), ("best", "Both pass on the best of three only"),
              ("one", "One of two sentences passes"), ("none", "Neither sentence passes"),
              ("nt", "In the model, not tested: no matching public sentence")]
    tt = dict(t, **{l: "nt" for l in not_tested})
    y, out = 310, []
    for k, label in groups:
        names = sorted(l for l in tt if tt[l] == k)
        out.append(f'<div style="position:absolute;left:96px;top:{y}px;width:1400px">'
                   f'<span class="mono" style="display:inline-block;width:86px;font-size:34px;font-weight:600;color:{CRIMSON if k in ("mid", "best") else INK}">{len(names)}</span>'
                   + "".join(f'<span class="sq {k}"></span>' for _ in names) +
                   f'<span style="font-size:27px;margin-left:14px">{html.escape(label)}</span>'
                   f'<div class="mono" style="margin:12px 0 0 86px;font-size:20px;color:{GREY}">{html.escape(" · ".join(names))}</div></div>')
        y += 112
    tested = len(t)
    out.append(f'<div style="position:absolute;left:96px;right:96px;top:{y + 4}px;border-top:3px solid {INK}"></div>'
               f'<div style="position:absolute;left:96px;top:{y + 26}px;width:1400px;font-size:25px;line-height:1.45">'
               f'<span class="mono" style="font-weight:600">{tested} / {tested + len(not_tested)}</span> routes of the 17-language checkpoint tested. '
               f'Later runs add <span class="mono" style="font-weight:600">31</span> and then <span class="mono" style="font-weight:600">6</span> routes for languages of Nepal. '
               f'None of those routes is part of this check.</div>')
    body = head("WHAT WE COULD TEST", "17 language routes · one square per language · automatic recogniser check, best CER at or below .15") + "".join(out)
    return 1600, y + 190, body


def fig_sizes():
    import math
    x0, x1, top, rh = 500, 1380, 330, 78
    X = lambda v: x0 + (x1 - x0) * (math.log10(v) - 5) / 4
    s = []
    for e, lab in ((5, "100K"), (6, "1M"), (7, "10M"), (8, "100M"), (9, "1B")):
        s.append(f'<line x1="{X(10 ** e)}" x2="{X(10 ** e)}" y1="{top - 20}" y2="{top + rh * len(SIZES)}" stroke="{RULE}" stroke-width="2"/>')
        s.append(f'<text x="{X(10 ** e)}" y="{top + rh * len(SIZES) + 30}" text-anchor="middle" font-size="18" fill="{GREY}">{lab}</text>')
    for i, (name, v, teacher) in enumerate(SIZES):
        cy = top + i * rh + rh / 2 - 10
        col = CRIMSON if teacher else GREY
        s.append(f'<text class="s" x="96" y="{cy + 9}" font-size="28">{name}</text>')
        s.append(f'<line x1="{X(1e5)}" x2="{X(v):.1f}" y1="{cy}" y2="{cy}" stroke="{col}" stroke-width="6"/>')
        s.append(f'<rect x="{X(v) - 11:.1f}" y="{cy - 11}" width="22" height="22" fill="{col}"/>')
        lab = f"{v:,}" if v != 2_270_000 else "2.27M"
        s.append(f'<text x="{X(v) + 26:.1f}" y="{cy + 7}" font-size="21" font-weight="600" fill="{col}">{lab}</text>')
    h = top + rh * len(SIZES) + 150
    svg = (f'<svg width="1600" height="{h}" style="position:absolute;left:0;top:0">{"".join(s)}'
           f'<text x="{(x0 + x1) / 2}" y="{top + rh * len(SIZES) + 64}" text-anchor="middle" font-size="18" fill="{GREY}">parameters, log scale</text></svg>')
    return 1600, h, head("TEACHER AND STUDENTS", "parameter counts · crimson: the internal teacher · grey: sanoTTS voices already released") + svg


def stat(x, y, w, big, small):
    return (f'<div style="position:absolute;left:{x}px;top:{y}px;width:{w}px;height:176px;background:#fff;border:3px solid {RULE};box-shadow:8px 8px 0 {RULE};padding:20px 22px">'
            f'<div class="mono" style="font-size:50px;font-weight:600;color:{CRIMSON};line-height:1">{big}</div>'
            f'<div class="mono" style="font-size:20px;color:{GREY};margin-top:16px;line-height:1.35">{small}</div></div>')


def card(rows, t, not_tested):
    both = sum(v in ("mid", "best") for v in t.values())
    body = (f'<div style="position:absolute;left:96px;top:160px;font:76px \'Press Start 2P\';letter-spacing:2px">khatra<span style="color:{CRIMSON}">TTS</span></div>'
            f'<div class="mono" style="position:absolute;left:100px;top:266px;font-size:30px;color:{GREY}">internal FlowLM-based teacher text-to-speech · one network, 17 language routes</div>'
            f'<div style="position:absolute;left:96px;top:356px">{squares(t)}</div>'
            f'<div class="mono" style="position:absolute;left:100px;top:422px;font-size:20px;color:{GREY}">15 tested languages · crimson: both test sentences pass an automatic recogniser check</div>'
            + stat(96, 520, 440, "324M", "parameters in the<br>teacher (FlowLM)")
            + stat(580, 520, 440, f"{both} / {len(t)}", "tested languages pass both<br>public test sentences")
            + stat(1064, 520, 440, ".078", "mean CER on the 15 newer<br>languages (Scribe v2)")
            + '<div class="src" style="bottom:70px">scored by speech recognisers · a listening test is next</div>')
    return 1600, 900, body


def og(rows, t, not_tested):
    both = sum(v in ("mid", "best") for v in t.values())
    body = (f'<style>.lab{{left:70px;top:58px;font-size:14px}}.mark{{right:70px;top:42px;transform:scale(.75);transform-origin:top right}}.sq{{width:52px;height:52px;margin-right:9px}}</style>'
            f'<div style="position:absolute;left:70px;top:124px;font:74px \'Press Start 2P\';letter-spacing:2px">khatra<span style="color:{CRIMSON}">TTS</span></div>'
            f'<div class="mono" style="position:absolute;left:74px;top:226px;font-size:31px;color:{INK}">a multilingual teacher for our small voices</div>'
            f'<div style="position:absolute;left:70px;top:306px">{squares(t)}</div>'
            f'<div class="mono" style="position:absolute;left:74px;top:398px;font-size:31px;font-weight:600;color:{CRIMSON};line-height:1.5">'
            f'324M parameters · 17 language routes<br>{both} of {len(t)} tested languages pass an automatic check<br>mean CER .078 on the 15 newer languages</div>')
    return 1200, 630, body


def main():
    data_path, font_dir, out_dir = sys.argv[1], Path(sys.argv[2]).resolve(), Path(sys.argv[3])
    data = json.load(open(data_path, encoding="utf-8"))
    rows, nt = data["rows"], data["not_tested"]
    t = tiers(rows)
    jobs = {"fig-cer.jpg": fig_cer(rows, t), "fig-coverage.jpg": fig_coverage(rows, t, nt), "fig-sizes.jpg": fig_sizes(),
            "hero-16x9.jpg": card(rows, t, nt), "og-1200x630.jpg": og(rows, t, nt)}
    with sync_playwright() as p:
        browser = p.chromium.launch()
        for name, (w, h, body) in jobs.items():
            src = out_dir / (name + ".html")
            src.write_text(page(w, h, body, font_dir), encoding="utf-8")
            pg = browser.new_page(viewport={"width": w, "height": h})
            pg.goto(src.as_uri())
            pg.evaluate("document.fonts.ready")
            pg.wait_for_timeout(400)
            pg.screenshot(path=str(out_dir / name), type="jpeg", quality=86)
            pg.close()
            src.unlink()
            print("wrote", name, w, h)
        browser.close()
    print("tiers:", {k: sorted(l for l in t if t[l] == k) for k in ("mid", "best", "one", "none")})


if __name__ == "__main__":
    main()
