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

specs = sys.argv[1].split("|")
text = sys.argv[2]
cap = float(sys.argv[3])

fam = {}
for s in specs:
    f, w = s.split(":")
    fam.setdefault(f, []).append(w)
url = "https://fonts.googleapis.com/css2?" + "&".join(
    "family=" + f.replace(" ", "+") + ":wght@" + ";".join(sorted(set(ws)))
    for f, ws in fam.items()) + "&display=block"

rows = "".join(
    f'<div class="row" data-f="{s.split(":")[0]}" data-w="{s.split(":")[1]}">'
    f'<span class="t">{text}</span></div>' for s in specs)
html = f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{url}">
<style>html,body{{margin:0;background:#fff}}
.row{{white-space:nowrap;line-height:1;margin:40px 20px}}
.t{{line-height:1;color:#000;font-kerning:normal}}</style></head>
<body>{rows}</body></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": 2400, "height": 1200})
    pg.set_content(html)
    pg.evaluate("document.fonts.ready")
    pg.wait_for_timeout(500)
    out = pg.evaluate("""(cap) => {
      const res = [];
      document.querySelectorAll('.row').forEach(row => {
        const t = row.querySelector('.t');
        const fam = row.dataset.f, wt = row.dataset.w;
        // cap height of H
        const c = document.createElement('canvas').getContext('2d');
        c.font = wt + ' 100px "' + fam + '"';
        const m = c.measureText('H');
        const capRatio = m.actualBoundingBoxAscent / 100;
        t.style.fontFamily = fam; t.style.fontWeight = wt;
        t.style.fontSize = (cap / capRatio) + 'px';
        const r = t.getBoundingClientRect();
        res.push({fam, wt, fs: parseFloat(t.style.fontSize), w: r.width});
      });
      return res;
    }""", cap)
    pg.wait_for_timeout(300)
    pg.screenshot(path="work/glyphsheet.png", full_page=True)
    b.close()

print(json.dumps(out, indent=0))
im = np.asarray(Image.open("work/glyphsheet.png").convert("L"))
ink = im < 128
rowsy = ink.sum(axis=1)
# find row bands
bands = []
s = None
for y, v in enumerate(rowsy):
    if v and s is None: s = y
    if not v and s is not None: bands.append((s, y - 1)); s = None
print("bands", bands)
for (info, (y0, y1)) in zip(out, bands):
    sub = ink[y0:y1 + 1]
    cols = sub.sum(axis=0)
    runs = []
    st = None
    for x, v in enumerate(cols):
        if v and st is None: st = x
        if not v and st is not None: runs.append((st, x - 1)); st = None
    print(info["fam"], info["wt"], "cap-px", y1 - y0 + 1, "fs", round(info["fs"]),
          "runs", [(a, bb, bb - a + 1) for a, bb in runs])
