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

SPECS = json.loads(open("work/specs.json").read())
SIZE = 200

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

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.7)}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>{rows}</body></html>"""
open("work/_hp.html", "w").write(html)

out = {}
with sync_playwright() as p:
    b = p.chromium.launch(args=["--font-render-hinting=none", "--force-color-profile=srgb"])
    pg = b.new_page(viewport={"width": 1800, "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(1200)
    for i, (f, w) in enumerate(SPECS):
        buf = pg.query_selector(f"#r{i}").screenshot()
        im = np.array(Image.open(io.BytesIO(buf)).convert("L")).astype(int)
        ink = im > 128
        colhas = ink.any(axis=0)
        idx = np.where(colhas)[0]
        runs = []
        s = prev = idx[0]
        for x in idx[1:]:
            if x > prev + 2:
                runs.append((s, prev)); s = x
            prev = x
        runs.append((s, prev))
        glyphs = []
        for a, bb in runs:
            sub = ink[:, a:bb + 1]
            yy = np.where(sub.any(axis=1))[0]
            glyphs.append([int(a), int(bb), int(yy.min()), int(yy.max())])
        out[f"{f}|{w}"] = glyphs
    b.close()
print(json.dumps(out))
