#!/usr/bin/env python3
"""Score candidate faces against a mock text line by pixel MAE.

For each candidate: solve tracking so the ink width matches, sweep the size a
little, render, align ink boxes, compare.
"""
import numpy as np
from PIL import Image
from playwright.sync_api import sync_playwright

ROOT = "/home/ubuntu/standalone/builds/32-pentagram-2"
LINK = ("https://fonts.googleapis.com/css2?"
        "family=Inter+Tight:ital,wght@0,600..900"
        "&family=Archivo:ital,wght@0,600..900"
        "&family=Roboto:ital,wght@0,700..900"
        "&family=Figtree:ital,wght@0,700..900"
        "&family=Hanken+Grotesk:ital,wght@0,700..900"
        "&family=Familjen+Grotesk:ital,wght@0,600..700"
        "&family=Instrument+Sans:ital,wght@0,600..700"
        "&family=Public+Sans:ital,wght@0,700..900"
        "&family=Manrope:ital,wght@0,700..800"
        "&display=block")
FS = ("https://api.fontshare.com/v2/css?"
      "f[]=switzer@400,500,600,700,800,900&display=block")

TEXT = "We print the"
# mock line 1 ink box and its region (shadow included on the right/bottom)
MX0, MY0, MX1, MY1 = 69, 177, 984, 302
TARGET_W = MX1 - MX0 + 1
MOCK = np.array(Image.open(f"{ROOT}/mock.jpg").convert("RGB"), dtype=float)

CANDS = [
    ("Inter Tight", "800"), ("Inter Tight", "900"),
    ("Switzer", "800"), ("Switzer", "900"),
    ("Roboto", "900"), ("Archivo", "800"), ("Archivo", "700"),
    ("Nimbus Sans", "700"), ("Familjen Grotesk", "700"),
    ("Figtree", "900"), ("Instrument Sans", "700"),
    ("Public Sans", "800"), ("Manrope", "800"),
    ("Hanken Grotesk", "900"),
]


def ink_bbox(arr, thr=150):
    g = arr.mean(2)
    m = g < thr
    ys, xs = np.where(m)
    return xs.min(), ys.min(), xs.max(), ys.max()


def main():
    rows = []
    with sync_playwright() as p:
        b = p.chromium.launch(args=["--font-render-hinting=none",
                                    "--force-color-profile=srgb"])
        pg = b.new_page(viewport={"width": 1200, "height": 300})
        pg.set_content(f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{LINK}"><link rel="stylesheet" href="{FS}">
<style>html,body{{margin:0;background:#f1e4d3}}
#t{{position:absolute;left:40px;top:40px;color:#e6432a;line-height:1;
white-space:pre;font-size:100px}}</style></head><body><span id="t"></span>
</body></html>""")
        pg.wait_for_timeout(2500)
        for fam, wt in CANDS:
            base = pg.evaluate("""async ([f,w,t]) => {
              await document.fonts.load(`${w} 100px "${f}"`);
              await document.fonts.ready;
              const cv=document.createElement('canvas');
              const ctx=cv.getContext('2d');
              ctx.font=`${w} 100px "${f}"`;
              const x=ctx.measureText(t);
              return {w:x.actualBoundingBoxRight+x.actualBoundingBoxLeft,
                      xh:ctx.measureText('x').actualBoundingBoxAscent,
                      cap:ctx.measureText('H').actualBoundingBoxAscent,
                      asc:ctx.measureText('d').actualBoundingBoxAscent};
            }""", [fam, wt, TEXT])
            best = None
            for scale in (0.94, 0.97, 1.0, 1.03, 1.06):
                # size from x-height 86 (measured from a lowercase run)
                size = 86.0 / base["xh"] * 100 * scale
                track = (TARGET_W - base["w"] * size / 100) / (len(TEXT) - 1)
                pg.evaluate("""async ([f,w,t,size,track]) => {
                  await document.fonts.load(`${w} 10px "${f}"`);
                  await document.fonts.ready;
                  const e=document.getElementById('t');
                  e.style.fontFamily=`"${f}"`; e.style.fontWeight=w;
                  e.style.fontSize=size+'px';
                  e.style.letterSpacing=track+'px';
                  e.textContent=t;
                }""", [fam, wt, TEXT, size, track])
                pg.wait_for_timeout(80)
                buf = pg.screenshot()
                import io
                arr = np.array(Image.open(io.BytesIO(buf)).convert("RGB"),
                               dtype=float)
                x0, y0, x1, y1 = ink_bbox(arr)
                # align render ink box onto mock ink box
                dx, dy = MX0 - x0, MY0 - y0
                h = min(y1 - y0, 200)
                w = min(x1 - x0, 930)
                reg_mock = MOCK[MY0:MY0 + h, MX0:MX0 + w]
                reg_ren = arr[y0:y0 + h, x0:x0 + w]
                mae = np.abs(reg_mock - reg_ren).mean()
                if best is None or mae < best[0]:
                    best = (mae, size, track, x1 - x0, y1 - y0,
                            base["cap"] * size / 100)
            rows.append((fam, wt, best))
            print(f"{fam:20s} {wt:>3s} mae={best[0]:5.2f} size={best[1]:6.1f} "
                  f"trk={best[2]:+.2f} w={best[3]} h={best[4]} cap={best[5]:.1f}")
        b.close()
    rows.sort(key=lambda r: r[2][0])
    print("\nranked:")
    for fam, wt, best in rows:
        print(f"  {best[0]:5.2f}  {fam} {wt}")


if __name__ == "__main__":
    main()
