#!/usr/bin/env python3
"""Render candidate fonts in Chromium and measure per-glyph metrics."""
import json
import os
import sys

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

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

CANDS = [
    ("Archivo Black", 400, None,
     "Archivo+Black"),
    ("Archivo", 900, 125, "Archivo:wdth,wght@62..125,100..900"),
    ("Archivo", 900, 100, "Archivo:wdth,wght@62..125,100..900"),
    ("Anybody", 900, 125, "Anybody:wdth,wght@50..150,100..900"),
    ("Anybody", 900, 100, "Anybody:wdth,wght@50..150,100..900"),
    ("Manrope", 800, None, "Manrope:wght@200..800"),
    ("Inter", 900, None, "Inter:wght@100..900"),
    ("Roboto", 900, None, "Roboto:wght@100..900"),
    ("Hanken Grotesk", 900, None, "Hanken+Grotesk:wght@100..900"),
    ("Libre Franklin", 900, None, "Libre+Franklin:wght@100..900"),
    ("Instrument Sans", 700, None, "Instrument+Sans:wght@400..700"),
    ("Bricolage Grotesque", 800, None,
     "Bricolage+Grotesque:opsz,wdth,wght@12..96,75..100,200..800"),
]

FAMILIES = sorted({c[3].split(":")[0] for c in CANDS})
CSS = ("https://fonts.googleapis.com/css2?" +
       "&".join("family=" + f for f in FAMILIES) + "&display=block")

SIZE = 500
ROW = 700


def main():
    rows = []
    for i, (fam, wt, wdth, _) in enumerate(CANDS):
        var = ""
        if wdth is not None:
            var = f"font-variation-settings:'wdth' {wdth},'wght' {wt};"
        rows.append(
            f'<div class="row" style="top:{i*ROW}px;'
            f'font-family:\'{fam}\';font-weight:{wt};{var}">SKIN.</div>')
    html = f"""<!doctype html><html><head><meta charset=utf-8>
<link href="{CSS}" rel=stylesheet>
<style>
html,body{{margin:0;background:#000;}}
.row{{position:absolute;left:40px;top:0;color:#fff;font-size:{SIZE}px;
line-height:1;white-space:nowrap;}}
</style></head><body>{''.join(rows)}</body></html>"""
    path = os.path.join(ROOT, "work", "_probe2.html")
    open(path, "w").write(html)
    out = os.path.join(ROOT, "work", "probe2.png")
    with sync_playwright() as p:
        b = p.chromium.launch(args=["--force-color-profile=srgb",
                                    "--font-render-hinting=none",
                                    "--disable-lcd-text"])
        pg = b.new_page(viewport={"width": 4096, "height": ROW * len(CANDS)},
                        device_scale_factor=1)
        pg.goto("file://" + path)
        pg.wait_for_timeout(2500)
        try:
            pg.evaluate("document.fonts.ready")
        except Exception:
            pass
        pg.wait_for_timeout(500)
        pg.screenshot(path=out)
        b.close()

    im = np.asarray(Image.open(out).convert("L"))
    print("mock target: cap 354  ink S378 K383 I127 N380 dot120  "
          "adv 398 399 162 400  stem 124")
    for i, (fam, wt, wdth, _) in enumerate(CANDS):
        band = im[i * ROW:(i + 1) * ROW]
        m = band > 128
        ys, xs = np.where(m)
        if not len(ys):
            print(f"{fam} {wt} {wdth}: EMPTY")
            continue
        cap = ys.max() - ys.min() + 1
        cols = m.sum(0)
        runs, s, gap = [], None, 0
        for x, v in enumerate(cols):
            if v > 0:
                if s is None:
                    s = x
                gap = 0
            elif s is not None:
                gap += 1
                if gap > 25:
                    runs.append((s, x - gap))
                    s = None
        if s is not None:
            runs.append((s, len(cols) - 1))
        widths = [b - a + 1 for a, b in runs]
        adv = [runs[j + 1][0] - runs[j][0] for j in range(len(runs) - 1)]
        # stem: median run width in the middle row of the third glyph (I)
        mid = (ys.min() + ys.max()) // 2
        row = m[mid]
        rr, ss = [], None
        for x, v in enumerate(row):
            if v and ss is None:
                ss = x
            if not v and ss is not None:
                rr.append(x - ss)
                ss = None
        stem = int(np.median([r for r in rr if r > 20])) if rr else 0
        sc = 354 / cap
        print(f"{fam:22s} {wt} wdth={str(wdth):4s} cap{cap:4d} "
              f"W{[round(w*sc) for w in widths]} "
              f"adv{[round(a*sc) for a in adv]} stem{round(stem*sc):4d}")


if __name__ == "__main__":
    main()
