#!/usr/bin/env python3
"""Rank candidate faces by pixel overlap with the mock's ink, solving size and
tracking per candidate.

Three passes, one full-page screenshot each:
  1. render at 100px, measure each band (mock band height includes overshoot, so
     both sides are normalised on the same measured band);
  2. rescale to the mock's band height, measure ink width per candidate;
  3. apply the analytic tracking that closes the width gap, render, score.
"""
import argparse
import os

import numpy as np
from PIL import Image

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PAGE = os.path.join(ROOT, "work/_fit.html")


def mock_ink(region, thresh=90):
    mock = np.asarray(Image.open(os.path.join(ROOT, "mock.jpg")).convert("L"), dtype=float)
    plate = np.asarray(Image.open(os.path.join(ROOT, "src/assets/plate.jpg")).convert("L"), dtype=float)
    x0, y0, x1, y1 = region
    d = np.abs(mock[y0:y1, x0:x1] - plate[y0:y1, x0:x1])
    return (d > thresh).astype(np.float32)


def trim(m):
    ys, xs = np.nonzero(m)
    return m[ys.min():ys.max() + 1, xs.min():xs.max() + 1]


def score(a, b, radius=8):
    H = max(a.shape[0], b.shape[0]) + 2 * radius
    W = max(a.shape[1], b.shape[1]) + 2 * radius
    A = np.zeros((H, W), np.float32)
    A[radius:radius + a.shape[0], radius:radius + a.shape[1]] = a
    best = (9e9, 0, 0)
    for dy in range(-radius, radius + 1):
        for dx in range(-radius, radius + 1):
            B = np.zeros((H, W), np.float32)
            y0, x0 = radius + dy, radius + dx
            if y0 < 0 or x0 < 0 or y0 + b.shape[0] > H or x0 + b.shape[1] > W:
                continue
            B[y0:y0 + b.shape[0], x0:x0 + b.shape[1]] = b
            v = np.abs(A - B).sum() / np.maximum(np.maximum(A, B).sum(), 1)
            if v < best[0]:
                best = (v, dx, dy)
    return best


def render_page(rows, link):
    """rows: list of (id, css, text). Returns list of crop masks."""
    body = "\n".join(
        f'<div class="r" id="{i}" style="{css}">{text}</div>' for i, css, text in rows)
    open(PAGE, "w").write(f"""<!doctype html><html><head><meta charset="utf-8">{link}
<style>html,body{{margin:0;background:#fff;color:#000}}
.r{{line-height:1.6;white-space:nowrap;display:block;padding:0 40px}}</style>
</head><body>{body}</body></html>""")
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        b = p.chromium.launch(args=["--force-color-profile=srgb", "--font-render-hinting=none"])
        pg = b.new_page(viewport={"width": 1200, "height": 800}, device_scale_factor=1)
        pg.goto("file://" + PAGE)
        pg.wait_for_timeout(150)
        try:
            pg.evaluate("document.fonts.ready")
        except Exception:
            pass
        pg.wait_for_timeout(400)
        rects = pg.evaluate(
            "() => [...document.querySelectorAll('.r')].map(e => {"
            "const r = e.getBoundingClientRect();"
            "return [r.x, r.y + window.scrollY, r.width, r.height];})")
        pg.screenshot(path=os.path.join(ROOT, "work/_fit.png"), full_page=True)
        b.close()
    im = np.asarray(Image.open(os.path.join(ROOT, "work/_fit.png")).convert("L"), dtype=float)
    ink = (im < 140).astype(np.float32)
    out = []
    for (x, y, w, h) in rects:
        sub = ink[int(y):int(y + h) + 1, int(x):int(x + w) + 1]
        out.append(sub if sub.size else np.zeros((1, 1), np.float32))
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--text", required=True)
    ap.add_argument("--region", required=True)
    ap.add_argument("--fonts", required=True)
    ap.add_argument("--link", default=None)
    ap.add_argument("--top", type=int, default=12)
    ap.add_argument("--base", type=float, default=100.0)
    args = ap.parse_args()

    target = trim(mock_ink([int(v) for v in args.region.split(",")]))
    th, tw = target.shape
    print(f"mock ink {tw}x{th}")
    fams = []
    for spec in args.fonts.split(","):
        p = spec.split(":")
        fams.append((p[0], p[1] if len(p) > 1 else "400"))
    link = f'<link href="{args.link}" rel="stylesheet">' if args.link else ""
    txt = args.text.replace(" ", "&nbsp;")

    # pass 1: band height ratio at 100px
    rows = [(f"a{i}", f"font-family:'{f}';font-weight:{w};font-size:{args.base}px", txt)
            for i, (f, w) in enumerate(fams)]
    m1 = render_page(rows, link)
    ratio = [trim(m).shape[0] / args.base for m in m1]
    size = [round(th / r, 2) for r in ratio]

    # pass 2: at normalised size, ink width
    rows = [(f"b{i}", f"font-family:'{f}';font-weight:{w};font-size:{size[i]}px", txt)
            for i, (f, w) in enumerate(fams)]
    m2 = render_page(rows, link)
    w2 = [trim(m).shape[1] for m in m2]
    ngap = len(args.text) - 1
    track = [round((tw - w2[i]) / (ngap * size[i]), 4) for i in range(len(fams))]

    # pass 3: with tracking, score
    rows = [(f"c{i}", f"font-family:'{f}';font-weight:{w};font-size:{size[i]}px;"
                      f"letter-spacing:{track[i]}em", txt)
            for i, (f, w) in enumerate(fams)]
    m3 = render_page(rows, link)
    out = []
    for i, (f, w) in enumerate(fams):
        sub = trim(m3[i])
        v, dx, dy = score(target, sub)
        out.append((v, f, w, size[i], track[i], sub.shape[1], sub.shape[0]))
    out.sort()
    print(f"{'candidate':26s} {'wt':>4s} {'size':>7s} {'track':>7s} {'inkW':>5s} {'inkH':>5s} {'mism':>7s}")
    for v, f, w, s, t, wid, h in out[:args.top]:
        print(f"{f:26s} {w:>4s} {s:7.2f} {t:+7.3f} {wid:5d} {h:5d} {v * 100:6.2f}%")


if __name__ == "__main__":
    main()
