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

TEXT = sys.argv[1]
TARGET_W = float(sys.argv[2])
CAP = float(sys.argv[3])
MX, MY = float(sys.argv[4]), float(sys.argv[5])
SPECS = [tuple(s.rsplit(":", 1)) for s in sys.argv[6].split(",")]
SPECS = [(f, int(w)) for f, w in SPECS]
LOCAL = {"Nimbus Sans", "Liberation Sans", "Liberation Serif", "DejaVu Sans",
         "Nimbus Roman", "P052", "C059", "URW Bookman", "Lato"}
google = sorted({f for f, w in SPECS if f not in LOCAL})
css = "https://fonts.googleapis.com/css2?" + "&".join(
    "family=" + f.replace(" ", "+") + ":wght@400;500;700" for f in google) + "&display=block"

def bbox(a, thr=120):
    ys, xs = np.where(a > thr)
    return xs.min(), ys.min(), xs.max(), ys.max()

mock = np.array(Image.open("mock.jpg").convert("L")).astype(int)
ry0, ry1 = int(MY)-22, int(MY)+int(CAP)+45
rx0, rx1 = int(MX)-22, int(MX)+int(TARGET_W)+22
ref = mock[ry0:ry1, rx0:rx1]

results = []
with sync_playwright() as p:
    b = p.chromium.launch(args=["--force-color-profile=srgb",
                                "--font-render-hinting=none",
                                "--disable-lcd-text", "--disable-gpu"])
    pg = b.new_page(viewport={"width": 1200, "height": 260}, device_scale_factor=1)
    link = f'<link rel=stylesheet href="{css}">' if google else ""
    pg.set_content(f"""<!doctype html><html><head><meta charset=utf-8>
{link}
<style>html,body{{margin:0;background:#1a1a1a}}
#line{{position:absolute;left:40px;top:40px;white-space:nowrap;color:#fff;line-height:1;font-kerning:normal}}</style>
</head><body><div id=line></div></body></html>""")
    try:
        pg.wait_for_function("document.fonts.status === 'loaded'", timeout=120000)
    except Exception:
        pass
    pg.wait_for_timeout(1200)
    for fam, wt in SPECS:
        js = """async ([fam, wt, text, cap, tw]) => {
          try { await document.fonts.load(`${wt} 400px "${fam}"`); } catch(e) {}
          await document.fonts.ready;
          const cv = document.createElement('canvas');
          const ctx = cv.getContext('2d');
          const ref = 400;
          ctx.font = `${wt} ${ref}px "${fam}"`;
          const capR = ctx.measureText('H').actualBoundingBoxAscent / ref;
          const wR = ctx.measureText(text).width / ref;
          const size = cap / capR;
          const target = tw / size;
          const track = (target - wR) / (text.length - 1);
          return {size, track, capR};
        }"""
        m = pg.evaluate(js, [fam, wt, TEXT, CAP, TARGET_W])
        pg.evaluate("""([text,fam,wt,size,track]) => {
          const el = document.getElementById('line');
          el.textContent = text;
          el.style.fontFamily = `"${fam}"`;
          el.style.fontWeight = wt;
          el.style.fontSize = size + 'px';
          el.style.letterSpacing = track + 'em';
        }""", [TEXT, fam, wt, m["size"], m["track"]])
        pg.wait_for_timeout(50)
        a = np.array(Image.open(io.BytesIO(pg.screenshot())).convert("L")).astype(int)
        bb = bbox(a, 60 if wt >= 500 else 100)
        crop = a[bb[1]:bb[3]+1, bb[0]:bb[2]+1]
        canvas = np.full(mock.shape, 26, dtype=int)
        h, w = crop.shape
        canvas[int(MY):int(MY)+h, int(MX):int(MX)+w] = crop
        reg = canvas[ry0:ry1, rx0:rx1]
        mae = np.abs(reg - ref).mean()
        mask = (ref > 100) | (reg > 100)
        mae_ink = np.abs(reg-ref)[mask].mean() if mask.any() else 0
        results.append((mae, mae_ink, fam, wt, round(m["size"],2), round(m["track"],4), w, h))
        print(f"{fam:20s} {wt:4d} MAE {mae:6.2f} ink {mae_ink:6.2f} "
              f"size {m['size']:6.2f} tr {m['track']:+.4f} inkbox {w}x{h}")
    b.close()
print("\nBEST")
for r in sorted(results)[:8]:
    print(r)
