import sys, numpy as np
from playwright.sync_api import sync_playwright

FONTS = sys.argv[1].split(",")
TEXT = ["Considered", "formulations,", "made in Melbourne."]
WANT = [549.0, 638.0, 873.0]
CAP = 89.0
fams = "&".join("family=" + f.replace(" ", "+") + ":wght@300;400;500;600" for f in FONTS)
html = ("<!doctype html><html><head><meta charset='utf-8'>"
        f"<link rel='stylesheet' href='https://fonts.googleapis.com/css2?{fams}&display=block'>"
        "</head><body></body></html>")
open("work/probe.html", "w").write(html)
with sync_playwright() as p:
    b = p.chromium.launch(channel="chrome")
    pg = b.new_page(viewport={"width": 1600, "height": 900})
    pg.goto("file:///home/ubuntu/standalone/builds/25-aesop-1/work/probe.html")
    pg.wait_for_function("document.fonts.status === 'loaded'", timeout=60000)
    pg.wait_for_timeout(400)
    js = """async ([fonts, texts]) => {
      const out = [];
      for (const f of fonts) {
        await document.fonts.load(`400 100px "${f}"`);
        const cv = document.createElement('canvas');
        const ctx = cv.getContext('2d');
        ctx.font = `400 100px "${f}"`;
        const cap = ctx.measureText('H').actualBoundingBoxAscent;
        const xh = ctx.measureText('x').actualBoundingBoxAscent;
        const w = texts.map(t => ctx.measureText(t).width);
        const g = {};
        for (const c of ['C','o','n','e','M','m','d']) {
          const mm = ctx.measureText(c);
          g[c] = mm.actualBoundingBoxLeft + mm.actualBoundingBoxRight;
        }
        out.push({f, cap, xh, w, g});
      }
      return out;
    }"""
    rows = pg.evaluate(js, [FONTS, TEXT])
    print("mock glyph ink: C=71 o=55 n=58 e=48 M=152 m=71 xh=59")
    res=[]
    for r in rows:
        size0 = CAP / (r["cap"] / 100.0)
        # unknowns: size s (px), tracking t (em). width_i = s*w_i/100 + t*s*(n_i-1)
        A=[]; y=[]
        for t_, w_, want in zip(TEXT, r["w"], WANT):
            n=len(t_)-1
            A.append([w_/100.0, n]); y.append(want)
        A=np.array(A); y=np.array(y)
        sol, *_ = np.linalg.lstsq(A, y, rcond=None)
        s, tr = sol
        pred = A@sol
        err = pred-y
        res.append((np.abs(err).sum(), r['f'], s, tr, pred, r['xh']/r['cap'], r['g'], size0))
    for tot,f,s,tr,pred,xhr,g,size0 in sorted(res):
        gs = " ".join(f"{k}={v*s/100:.0f}" for k,v in g.items())
        print(f"{f:22s} size {s:6.2f} track {tr:+.4f}em err {tot:5.1f} "
              f"pred {pred[0]:5.0f}/{pred[1]:5.0f}/{pred[2]:5.0f} xh/cap {xhr:.3f} | {gs}")
    b.close()
