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

SPECS = [
    ("Roboto", 900), ("Inter", 900), ("Inter Tight", 900),
    ("Archivo", 900), ("Archivo Black", 400), ("Anton", 400),
    ("Barlow", 900), ("Work Sans", 900), ("Helvetica Neue", 700),
    ("DM Sans", 900), ("Manrope", 800), ("League Spartan", 900),
    ("Bebas Neue", 400), ("Oswald", 700), ("Figtree", 900),
]
SIZE = 200

def css_url(specs):
    fams = []
    for f, w in specs:
        fam = f.replace(" ", "+")
        fams.append(f"family={fam}:wght@{w}")
    return "https://fonts.googleapis.com/css2?" + "&".join(fams) + "&display=block"

html_rows = "".join(
    f'<div class="row"><span id="r{i}" style="font-family:\'{f}\';font-weight:{w}">roast</span></div>'
    for i, (f, w) in enumerate(SPECS))

html = f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{css_url(SPECS)}">
<style>
 html,body{{margin:0;background:#000}}
 .row{{position:relative;height:{int(SIZE*1.6)}px;white-space:nowrap}}
 span{{position:absolute;left:20px;top:20px;color:#fff;font-size:{SIZE}px;line-height:1;white-space:nowrap}}
</style></head><body>{html_rows}</body></html>"""

open("work/_hp.html", "w").write(html)

with sync_playwright() as p:
    b = p.chromium.launch(args=["--font-render-hinting=none", "--force-color-profile=srgb"])
    pg = b.new_page(viewport={"width": 1600, "height": 300}, device_scale_factor=1)
    pg.goto("file:///home/ubuntu/standalone/builds/29-bluebottle-2/work/_hp.html")
    try:
        pg.wait_for_function("document.fonts.status === 'loaded'", timeout=60000)
    except Exception:
        pass
    pg.wait_for_timeout(1500)
    loaded = pg.evaluate("""() => {
      return %s.map(([f,w]) => document.fonts.check(`${w} ${%d}px "${f}"`));
    }""" % (json.dumps(SPECS), SIZE))

    for i, (f, w) in enumerate(SPECS):
        el = pg.query_selector(f"#r{i}")
        buf = el.screenshot()
        im = np.array(Image.open(io.BytesIO(buf)).convert("L")).astype(int)
        ink = im > 128
        if not ink.any():
            print(f"{f} {w}: NO INK")
            continue
        ys, xs = np.where(ink)
        # x-height from the 'r' (first glyph): column runs
        colhas = ink.any(axis=0)
        idx = np.where(colhas)[0]
        gaps = []
        s = idx[0]; prev = idx[0]
        for x in idx[1:]:
            if x > prev + 2:
                gaps.append((s, prev)); s = x
            prev = x
        gaps.append((s, prev))
        # x-height: take column band of first run (the r) and measure top of flat
        r0, r1 = gaps[0]
        sub = ink[:, r0:r1 + 1]
        yy = np.where(sub.any(axis=1))[0]
        xh = yy.max() - yy.min() + 1
        runs = " ".join(f"{a}-{b}" for a, b in gaps)
        print(f"{f} {w}: loaded={loaded[i]} xh={xh} runs={runs}")
    b.close()
