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

CANDS = [
    ("Epilogue", 900), ("Epilogue", 800), ("Figtree", 900), ("Saira", 900),
    ("Mukta", 800), ("Poppins", 900), ("Geist", 900), ("Barlow", 900),
    ("Kanit", 800), ("Roboto", 900), ("Inter Tight", 900), ("Archivo", 900),
]
LINE = sys.argv[1] if len(sys.argv) > 1 else "THREE OF THEM FREE."
MOCKBOX = tuple(int(v) for v in (sys.argv[2] if len(sys.argv) > 2 else "20,295,1520,420").split(","))

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}">{LINE}</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:200px;
        margin:0 0 40px 20px; padding:0; }}
</style></head><body>{rows}</body></html>"""
open("work/probe/cmp.html", "w").write(html)

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


def ink_of(a, thr=150):
    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/cmp.html"))
    pg.wait_for_timeout(4500)
    cap_target = mk_ink.shape[0]
    print("mock ink", mk_ink.shape)
    for i, (fam, wt) in enumerate(CANDS):
        a = shot(pg, i, 200, 0)
        cap200 = ink_of(a).shape[0]
        size = cap_target * 200.0 / cap200
        a = shot(pg, i, size, 0)
        ai = ink_of(a)
        dW = mk_ink.shape[1] - ai.shape[1]
        track = (dW / (len(LINE) - 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:20s} {wt:4d} size {size:6.2f} cap {ai.shape[0]:3d} w {ai.shape[1]:4d} "
              f"track {track:+.4f}  MAE {mae:6.2f}")
    br.close()
json.dump(res, open("work/probe/res.json", "w"), indent=1)
print()
for r in sorted(res, key=lambda r: r["mae"])[:8]:
    print(r)
