import numpy as np
from PIL import Image
from playwright.sync_api import sync_playwright

fam = "Archivo"
wt = "900"
letters = "TONIGHT"
stretches = [62, 70, 80, 90, 100, 110]
cap = 323.0

url = ("https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,900"
       "&display=block")
rows = ""
for st in stretches:
    for ch in letters:
        rows += (f'<div class="row"><span class="t" data-st="{st}" style="font-stretch:{st}%">{ch}</span></div>')
html = f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{url}">
<style>
html,body{{margin:0;background:#fff}}
.row{{line-height:1;margin:30px 20px}}
.t{{font-family:"{fam}";font-weight:{wt};font-size:100px;line-height:1;
color:#000;display:inline-block}}
</style></head><body>{rows}</body></html>"""
open("work/_wtest.html", "w").write(html)
with sync_playwright() as p:
    b = p.chromium.launch(args=["--font-render-hinting=none", "--force-color-profile=srgb",
                                "--disable-dev-shm-usage"])
    pg = b.new_page(viewport={"width": 900, "height": 1200})
    pg.goto("file:///home/ubuntu/standalone/builds/21-dishoom-3/work/_wtest.html")
    try:
        pg.evaluate("document.fonts.ready")
    except Exception:
        pass
    pg.wait_for_timeout(800)
    # set sizes using measured cap at 100px
    infos = pg.evaluate("""() => [...document.querySelectorAll('.t')].map(e => {
        e.style.fontSize = '100px';
        e.style.fontStretch = e.dataset.st + '%';
        return [e.dataset.st, e.textContent];
    })""")
    pg.wait_for_timeout(300)
    pg.screenshot(path="work/wtest.png", full_page=True)
    b.close()

g = np.asarray(Image.open("work/wtest.png").convert("L")).astype(int)
ink = g < 128
rowsum = ink.sum(axis=1)
bands = []
s = None
for y, v in enumerate(rowsum):
    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", len(bands), bands[:3], bands[-3:])
# cap of first T at 100px is bands[0] height
cap100 = bands[0][1] - bands[0][0] + 1
fs = 100 * cap / cap100
print("cap100", cap100, "fs", fs)
# re-render at target size
html2 = html.replace("font-size:100px", f"font-size:{fs:.1f}px")
open("work/_wtest.html", "w").write(html2)
with sync_playwright() as p:
    b = p.chromium.launch(args=["--font-render-hinting=none", "--force-color-profile=srgb",
                                "--disable-dev-shm-usage"])
    pg = b.new_page(viewport={"width": 1100, "height": 1200})
    pg.goto("file:///home/ubuntu/standalone/builds/21-dishoom-3/work/_wtest.html")
    try:
        pg.evaluate("document.fonts.ready")
    except Exception:
        pass
    pg.wait_for_timeout(800)
    pg.screenshot(path="work/wtest2.png", full_page=True)
    b.close()
g = np.asarray(Image.open("work/wtest2.png").convert("L")).astype(int)
ink = g < 128
rowsum = ink.sum(axis=1)
bands = []
s = None
for y, v in enumerate(rowsum):
    if v and s is None: s = y
    if not v and s is not None: bands.append((s, y - 1)); s = None
print("bands2", len(bands))
for (st, ch), (y0, y1) in zip([(st, ch) for st in stretches for ch in letters], bands):
    sub = ink[y0:y1 + 1]
    ys, xs = np.where(sub)
    w = xs.max() - xs.min() + 1
    h = y1 - y0 + 1
    # stem from middle band rows
    lo, hi = int(y0 + 0.25 * h), int(y0 + 0.75 * h)
    runs = []
    for y in range(lo, hi):
        row = ink[y].astype(np.int8)
        d = np.diff(np.concatenate(([0], row, [0])))
        for a, bb in zip(np.where(d == 1)[0], np.where(d == -1)[0]):
            L = bb - a
            if 0 < L <= h * 0.5:
                runs.append(L)
    stem = np.median(runs) if runs else 0
    print(st, ch, "w", w, "h", h, "stem", stem)
