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

CANDS = [
    ("Roboto", 900), ("Roboto", 700),
    ("Inter", 900), ("Inter", 800),
    ("Inter Tight", 900), ("Inter Tight", 800),
    ("Manrope", 800),
    ("Barlow", 800), ("Barlow", 900),
    ("Figtree", 900),
    ("Archivo", 800), ("Archivo", 900),
    ("Archivo Black", 400),
    ("Public Sans", 900),
    ("Saira", 900),
    ("Asap", 900),
    ("Mukta", 800),
    ("Kanit", 800),
    ("Anton", 400),
    ("Oswald", 700),
    ("Roboto Condensed", 900),
    ("Helvetica Neue", 700),
]

TEXT = sys.argv[1] if len(sys.argv) > 1 else "FOUR GALLERIES."
W = 1600
FS = 200

def fams_url():
    famset = {}
    for f, w in CANDS:
        famset.setdefault(f, set()).add(w)
    parts = []
    for f, ws in famset.items():
        parts.append("family=" + f.replace(" ", "+") + ":wght@" + ";".join(str(w) for w in sorted(ws)))
    return "https://fonts.googleapis.com/css2?" + "&".join(parts) + "&display=block"

html = f"""<!doctype html><html><head><meta charset=utf-8>
<link rel=stylesheet href="{fams_url()}">
<style>
 body {{ margin:0; background:#fff; }}
 .row {{ color:#000; white-space:nowrap; width:{W}px; font-size:{FS}px; line-height:1.4; padding-left:20px; }}
</style></head><body>
""" + "".join(
    f'<div class=row id="r{i}" style="font-family:\'{f}\';font-weight:{w}">{TEXT}</div>'
    for i, (f, w) in enumerate(CANDS)
) + "</body></html>"

os.makedirs("work/probe", exist_ok=True)
open("work/probe/p.html", "w").write(html)

out = []
with sync_playwright() as p:
    b = p.chromium.launch()
    pg = b.new_page(viewport={"width": W, "height": 400})
    pg.goto("file://" + os.path.abspath("work/probe/p.html"))
    pg.wait_for_timeout(4000)
    for i, (f, w) in enumerate(CANDS):
        el = pg.query_selector(f"#r{i}")
        el.screenshot(path=f"work/probe/r{i}.png")
        out.append({"i": i, "fam": f, "wt": w, "file": f"work/probe/r{i}.png"})
    b.close()

rows = []
for r in out:
    im = np.array(Image.open(r["file"]).convert("L")).astype(float)
    m = im < 128
    ys, xs = np.where(m)
    if len(ys) == 0:
        continue
    x0, x1, y0, y1 = xs.min(), xs.max(), ys.min(), ys.max()
    cap = y1 - y0 + 1
    # stem: measure first glyph's vertical bar on scans in the middle 60% of cap
    stems = []
    for y in range(y0 + int(cap * 0.25), y0 + int(cap * 0.75)):
        row = m[y]
        # first run
        x = x0
        while x <= x1 and not row[x]:
            x += 1
        s = x
        while x <= x1 and row[x]:
            x += 1
        stems.append(x - s)
    stem = float(np.median(stems))
    rows.append((r["fam"], r["wt"], FS, cap, x1 - x0 + 1, round(stem, 1), round(stem / cap, 4)))

rows.sort(key=lambda t: t[5] / t[3], reverse=True)
print(f"{'family':22s} {'wt':>4s} {'size':>6s} {'cap':>4s} {'inkW':>5s} {'stem':>5s} {'stem/cap':>8s} {'size@cap115':>11s} {'W@cap115':>8s}")
for fam, wt, fs, cap, w, stem, sc in rows:
    s115 = 115 * fs / cap
    print(f"{fam:22s} {wt:4d} {fs:6d} {cap:4d} {w:5d} {stem:5.1f} {sc:8.4f} {s115:11.1f} {w*115/cap:8.1f}")
