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

TEXT = "The world\u2019s largest"
TARGET_W = 681
CAP = 65
MOCK_BOX = (42, 188, 721, 258)
SPECS = [
    ("Tinos", 400), ("Tinos", 700), ("Prata", 400), ("Newsreader", 500),
    ("Spectral", 400), ("Gelasio", 400), ("Lora", 400), ("PT Serif", 400),
    ("Faustina", 500), ("Merriweather", 400), ("Libre Caslon Text", 400),
    ("Noto Serif", 500), ("Crimson Text", 400), ("DM Serif Display", 400),
    ("Marcellus", 400), ("Gilda Display", 400), ("Cardo", 400), ("Literata", 400),
]
OLD_SPECS = [
    ("Tinos", 400), ("Tinos", 700),
    ("Prata", 400),
    ("Newsreader", 400), ("Newsreader", 500),
    ("Spectral", 400),
    ("Libre Caslon Text", 400),
    ("Crimson Text", 400),
    ("Gelasio", 400), ("Gelasio", 500),
    ("Playfair Display", 400), ("Playfair Display", 500),
    ("DM Serif Display", 400),
    ("Marcellus", 400),
    ("Gilda Display", 400),
    ("Lora", 400), ("Lora", 500),
    ("PT Serif", 400),
    ("Merriweather", 400),
    ("Faustina", 400), ("Faustina", 500),
    ("Bitter", 400),
    ("Libre Baskerville", 400),
    ("Source Serif 4", 400),
    ("Noto Serif", 400), ("Noto Serif", 500),
    ("Cormorant Garamond", 500),
    ("Sorts Mill Goudy", 400),
    ("Alegreya", 400),
    ("Vollkorn", 400),
    ("Gentium Book Plus", 400),
    ("Frank Ruhl Libre", 400),
    ("Petrona", 400),
    ("Literata", 400),
    ("Bodoni Moda", 400),
    ("Abhaya Libre", 400),
    ("Cardo", 400),
    ("Alice", 400),
]

fams = sorted({s[0] for s in SPECS})
css = "https://fonts.googleapis.com/css2?" + "&".join(
    "family=" + f.replace(" ", "+") + ":wght@400;500;700" for f in fams) + "&display=block"

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

def main():
    mock = np.array(Image.open("mock.jpg").convert("L")).astype(int)
    x0, y0, x1, y1 = MOCK_BOX
    ref = mock[y0-22:y1+22, x0-22:x1+22]
    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": 1100, "height": 300}, device_scale_factor=1)
        pg.set_content(f"""<!doctype html><html><head><meta charset=utf-8>
<link rel=stylesheet href="{css}">
<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(1500)
        for fam, wt in SPECS:
            js = """async ([fam, wt, text, cap, tw]) => {
              await document.fonts.load(`${wt} 400px "${fam}"`);
              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(60)
            buf = pg.screenshot()
            im = Image.open(io.BytesIO(buf)).convert("L")
            a = np.array(im).astype(int)
            bb = bbox(a)
            crop = a[bb[1]:bb[3]+1, bb[0]:bb[2]+1]
            # place into 1536x864 canvas at mock ink origin
            canvas = np.full((864, 1536), 26, dtype=int)
            h, w = crop.shape
            canvas[188:188+h, 42:42+w] = crop
            reg = canvas[y0-22:y1+22, x0-22:x1+22]
            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:22s} {wt:4d} MAE {mae:6.2f} inkMAE {mae_ink:6.2f} "
                  f"size {m['size']:6.2f} track {m['track']:+.4f} ink {w}x{h}")
        b.close()
    print("\nBEST:")
    for r in sorted(results)[:8]:
        print(r)

main()
