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

spec = sys.argv[1]
track_override = sys.argv[2] if len(sys.argv) > 2 else None
text = "TONIGHT"
cap = 323.0
left = 33.0
cap_top = 302.0
mock_lefts = [33, 222, 554, 839, 946, 1200, 1428]

bits = spec.split(":")
fam, wt = bits[0], bits[1]
wdth = bits[2] if len(bits) > 2 else None
if wdth:
    url = (f"https://fonts.googleapis.com/css2?family={fam.replace(' ','+')}"
           f":wdth,wght@{wdth}..{wdth},{wt}&display=block")
else:
    url = (f"https://fonts.googleapis.com/css2?family={fam.replace(' ','+')}"
           f":wght@{wt}&display=block")


def page(fs, top, track, width):
    return f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{url}">
<style>
html,body{{margin:0;padding:0;background:#f1e5d5;width:{width}px;height:864px;overflow:hidden}}
.h{{position:absolute;left:{left}px;top:{top}px;font-family:"{fam}";font-weight:{wt};
font-size:{fs}px;line-height:1;letter-spacing:{track}em;
color:#1b1b1b;white-space:nowrap;}}
</style></head><body><div class="h">{text}</div></body></html>"""


def shot(html, path, width=1536):
    open("work/_head.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": width, "height": 864})
        pg.goto("file:///home/ubuntu/standalone/builds/21-dishoom-3/work/_head.html")
        try:
            pg.evaluate("document.fonts.ready")
        except Exception:
            pass
        pg.wait_for_timeout(1000)
        pg.screenshot(path=path)
        b.close()
    g = np.asarray(Image.open(path).convert("L")).astype(int)
    return g < 128


def colruns(ink, x0=0, x1=None):
    x1 = x1 or ink.shape[1]
    cols = ink[280:660, x0:x1].sum(axis=0)
    runs, s = [], None
    for i, v in enumerate(cols):
        if v and s is None: s = i
        if not v and s is not None: runs.append((x0 + s, x0 + i - 1, i - s)); s = None
    if s is not None: runs.append((x0 + s, x1 - 1, x1 - x0 - s))
    return runs


# pass 1: cap measurement
ink = shot(page(100, 0, 0, 2400), "work/head_test0.png", 2400)
ys, xs = np.where(ink)
cap_px = ys.max() - ys.min() + 1
fs = 100 * cap / cap_px
ink = shot(page(round(fs, 2), 0, 0, 2400), "work/head_test1.png", 2400)
ys, xs = np.where(ink)
shift = cap_top - ys.min()
ink = shot(page(round(fs, 2), round(shift, 2), 0, 2400), "work/head_nat.png", 2400)
runs = colruns(ink)
# merge nothing; expect 7
if len(runs) != 7:
    print("WARN runs", runs)
lefts = [r[0] for r in runs][:7]
widths = [r[2] for r in runs][:7]
# least squares fit tracking (px per gap)
idx = list(range(1, len(lefts)))
tpx = np.polyfit(idx, [mock_lefts[i] - lefts[i] for i in idx], 1)[0]
t_em = tpx / fs
if track_override is not None:
    t_em = float(track_override)
ink = shot(page(round(fs, 2), round(shift, 2), round(t_em, 5), 1536),
           "work/head_fit.png", 1536)
runs2 = colruns(ink)
ys, xs = np.where(ink)
print(f"{spec} fs {fs:.1f} cap {cap_px} track {t_em:+.4f}em ({tpx:+.1f}px) "
      f"ink {xs.min()}..{xs.max()}")
print("  natural runs", runs)
print("  fitted  runs", runs2)

mock = np.asarray(Image.open("mock.jpg").convert("RGB")).astype(np.float32)
ren = np.asarray(Image.open("work/head_fit.png").convert("RGB")).astype(np.float32)
reg = (slice(295, 640), slice(20, 1536))
print("  headline-region MAE", round(float(np.abs(mock[reg] - ren[reg]).mean()), 2))
