import os, sys, json
import numpy as np
from PIL import Image
from playwright.sync_api import sync_playwright

# usage: probe_gen.py "<text>" "x0,y0,x1,y1" "Fam:wt,Fam:wt,..." [fit]
# fit: cap (default; fits ink box height) | width (fits ink width, then tracking 0)
TEXT = sys.argv[1]
BOX = tuple(int(v) for v in sys.argv[2].split(","))
CANDS = [tuple((c.split(":") + ["400"])[:2]) for c in sys.argv[3].split(",")]
CANDS = [(f, int(w)) for f, w in CANDS]
FIT = sys.argv[4] if len(sys.argv) > 4 else "cap"
THR = int(sys.argv[5]) if len(sys.argv) > 5 else 150
FS = float(sys.argv[6]) if len(sys.argv) > 6 else 200.0

fams = {}
for f, w in CANDS:
    fams.setdefault(f, set()).add(w)
url = "https://fonts.googleapis.com/css2?" + "&".join(
    "family=" + f.replace(" ", "+") + ":wght@" + ";".join(str(x) for x in sorted(ws))
    for f, ws in fams.items()) + "&display=block"

rows = "".join(
    f'<div class=ln id=c{i} style="font-family:\'{f}\';font-weight:{w}">{TEXT}</div>'
    for i, (f, w) in enumerate(CANDS))
html = f"""<!doctype html><html><head><meta charset=utf-8>
<link rel=stylesheet href="{url}">
<style>
 body {{ margin:0; background:#f2eee3; }}
 .ln {{ white-space:nowrap; color:#131212; line-height:1.5; font-size:{FS}px;
        margin:0 0 40px 20px; padding:0; }}
</style></head><body>{rows}</body></html>"""
open("work/probe/g.html", "w").write(html)

mock = np.array(Image.open("mock.jpg").convert("L")).astype(float)
mk = mock[BOX[1]:BOX[3], BOX[0]:BOX[2]]
m = mk < THR
ys, xs = np.where(m)
mk_ink = mk[ys.min():ys.max() + 1, xs.min():xs.max() + 1]


def ink_of(a, thr=THR):
    m = a < thr
    ys, xs = np.where(m)
    return a[ys.min():ys.max() + 1, xs.min():xs.max() + 1]


def compare(a, b):
    H = max(a.shape[0], b.shape[0]); W = max(a.shape[1], b.shape[1])
    A = np.full((H, W), 242.0); B = np.full((H, W), 242.0)
    A[:a.shape[0], :a.shape[1]] = a
    B[:b.shape[0], :b.shape[1]] = b
    return float(np.abs(A - B).mean())


def shot(pg, i, size, track):
    pg.evaluate("([i,size,track])=>{const d=document.getElementById('c'+i);"
                "d.style.fontSize=size+'px'; d.style.letterSpacing=(track*size)+'px';}",
                [i, size, track])
    pg.wait_for_timeout(25)
    pg.query_selector(f"#c{i}").screenshot(path="work/probe/_t.png")
    return np.array(Image.open("work/probe/_t.png").convert("L")).astype(float)


res = []
with sync_playwright() as p:
    br = p.chromium.launch(args=["--disable-gpu","--disable-software-rasterizer","--no-sandbox","--disable-dev-shm-usage"])
    pg = br.new_page(viewport={"width": 1700, "height": 900})
    pg.goto("file://" + os.path.abspath("work/probe/g.html"))
    pg.wait_for_timeout(4500)
    print("mock ink", mk_ink.shape)
    for i, (fam, wt) in enumerate(CANDS):
        a = shot(pg, i, FS, 0)
        i200 = ink_of(a)
        if FIT == "cap":
            size = mk_ink.shape[0] * FS / i200.shape[0]
        else:
            size = mk_ink.shape[1] * FS / i200.shape[1]
        a = shot(pg, i, size, 0)
        ai = ink_of(a)
        track = 0.0
        if FIT == "cap":
            dW = mk_ink.shape[1] - ai.shape[1]
            track = (dW / max(1, len(TEXT) - 1)) / size
        a = shot(pg, i, size, track)
        ai = ink_of(a)
        mae = compare(ai, mk_ink)
        res.append(dict(fam=fam, wt=wt, size=round(size, 2), cap=ai.shape[0],
                        inkw=ai.shape[1], track=round(track, 4), mae=round(mae, 2)))
        print(f"{fam:22s} {wt:4d} size {size:7.2f} ink {ai.shape[0]:3d}x{ai.shape[1]:4d} "
              f"(mock {mk_ink.shape[0]}x{mk_ink.shape[1]}) track {track:+.4f}  MAE {mae:6.2f}")
    br.close()
json.dump(res, open("work/probe/g_res.json", "w"), indent=1)
print()
for r in sorted(res, key=lambda r: r["mae"])[:8]:
    print(r)
