#!/usr/bin/env python3
"""Solve font-size + tracking for several mock line widths at once."""
import json
import sys

import numpy as np
from playwright.sync_api import sync_playwright

LINK = ("https://fonts.googleapis.com/css2?"
        "family=Inter+Tight:ital,wght@0,700..900"
        "&family=Archivo:ital,wght@0,700..900"
        "&family=Roboto:ital,wght@0,700..900"
        "&family=Barlow:ital,wght@0,700..900"
        "&family=Hanken+Grotesk:ital,wght@0,700..900"
        "&family=Figtree:ital,wght@0,700..900"
        "&family=Familjen+Grotesk:ital,wght@0,600..700"
        "&family=Anek+Latin:ital,wght@0,700..900"
        "&family=Manrope:ital,wght@0,700..800"
        "&display=block")
FS = "https://api.fontshare.com/v2/css?f[]=switzer@400,500,600,700,800,900&display=block"

cfg = json.load(open(sys.argv[1]))
lines = cfg["lines"]
lines = [(t, w, len(t) - 1) for t, w in lines]
cands = [(c.split(":")[0], c.split(":")[1]) for c in cfg["candidates"]]

with sync_playwright() as p:
    b = p.chromium.launch(args=["--font-render-hinting=none",
                                "--force-color-profile=srgb"])
    pg = b.new_page(viewport={"width": 1000, "height": 600})
    pg.set_content(f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{LINK}"><link rel="stylesheet" href="{FS}">
</head><body></body></html>""")
    pg.wait_for_timeout(2000)
    print(f"{'family':22s} {'wt':>3s} {'size':>6s} {'trk em':>7s} "
          f"{'cap':>5s} {'xh':>5s} {'resid':>6s}  widths")
    for fam, wt in cands:
        m = pg.evaluate("""async ([fam,wt,lines]) => {
          await document.fonts.load(`${wt} 100px "${fam}"`);
          await document.fonts.ready;
          const cv=document.createElement('canvas');
          const ctx=cv.getContext('2d');
          ctx.font=`${wt} 100px "${fam}"`;
          const wid = s => {
            const x=ctx.measureText(s);
            return (x.actualBoundingBoxRight + x.actualBoundingBoxLeft);
          };
          return {ws: lines.map(t=>wid(t)),
                  cap: ctx.measureText('H').actualBoundingBoxAscent,
                  xh: ctx.measureText('x').actualBoundingBoxAscent,
                  asc: ctx.measureText('d').actualBoundingBoxAscent};
        }""", [fam, wt, [t for t, _, _ in lines]])
        a = np.array(m["ws"]) / 100.0
        n = np.array([g for _, _, g in lines], dtype=float)
        w = np.array([w for _, w, _ in lines], dtype=float)
        # unknowns: S, u = S*t ; ink = S*a + u*n
        A = np.stack([a, n], 1)
        (S, u), res, *_ = np.linalg.lstsq(A, w, rcond=None)
        pred = A @ np.array([S, u])
        resid = float(np.sqrt(((pred - w) ** 2).mean()))
        print(f"{fam:22s} {wt:>3s} {S:6.1f} {u / S:7.4f} "
              f"{m['cap'] * S / 100:5.1f} {m['xh'] * S / 100:5.1f} "
              f"{resid:6.1f}  " + " ".join(f"{v:.0f}" for v in pred))
    b.close()
