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

CAND = json.loads(sys.argv[1])
mockim = np.array(Image.open("mock.jpg").convert("L").crop((0, 150, 1536, 600))).astype(int)
mockink = mockim > 140
# mock headline r left = 52, r bottom = 556 -> coords in crop
ML, MB = 52, 556 - 150


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


with sync_playwright() as p:
    b = p.chromium.launch(args=["--font-render-hinting=none", "--force-color-profile=srgb"])
    pg = b.new_page(viewport={"width": 1536, "height": 600}, device_scale_factor=1)
    tiles = []
    for f, w, s, t, extra in CAND:
        html = f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{css_url([(f, w)])}">
<style>html,body{{margin:0;background:#000}}
 span{{position:absolute;left:52px;top:60px;color:#fff;line-height:1;white-space:nowrap;
 font-family:'{f}';font-weight:{w};font-size:{s}px;letter-spacing:{t}em;{extra}}}</style>
</head><body><span>roast</span></body></html>"""
        pg.set_content(html)
        try:
            pg.wait_for_function("document.fonts.status === 'loaded'", timeout=30000)
        except Exception:
            pass
        pg.wait_for_timeout(500)
        g = np.array(Image.open(io.BytesIO(pg.screenshot())).convert("L")).astype(int) > 140
        ys, xs = np.nonzero(g)
        cl = xs.min()
        # r = first ~200 cols run
        coltouch = g[:, cl:cl + 70].any(axis=1)
        cb = np.where(coltouch)[0].max()
        # shift to align
        dy, dx = MB - cb, ML - cl
        sh = np.zeros_like(mockink)
        ys2, xs2 = np.nonzero(g)
        ys2 = ys2 + dy; xs2 = xs2 + dx
        ok = (ys2 >= 0) & (ys2 < sh.shape[0]) & (xs2 >= 0) & (xs2 < sh.shape[1])
        sh[ys2[ok], xs2[ok]] = True
        rgb = np.zeros((*mockink.shape, 3), np.uint8)
        rgb[mockink] = [255, 40, 40]
        rgb[sh] = [40, 255, 40]
        rgb[mockink & sh] = [255, 230, 60]
        xor = (mockink ^ sh)[100:520, 0:1536].sum()
        uni = (mockink | sh)[100:520, 0:1536].sum()
        print(f"{f} {w}: xor/union = {xor/uni:.4f}  (mock ink {mockink[100:520].sum()})")
        tiles.append((f"{f} {w}", Image.fromarray(rgb)))
    b.close()

W = 1536
out = Image.new("RGB", (W, sum(t.height for _, t in tiles)))
y = 0
for name, t in tiles:
    out.paste(t, (0, y)); y += t.height
out.save("work/headline_overlay.png")
print([n for n, _ in tiles])

# report mismatches
