#!/usr/bin/env python3
"""Rank candidate faces by actual pixel overlap with the mock's ink.

Renders each candidate (family:weight[:letterspacing em]) to a bitmap normalised
to the mock's cap height, brute-force aligns, and reports mismatch %.
"""
import argparse
import json
import os

import numpy as np
from PIL import Image

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


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 render(html_path, n):
    """Screenshot each .r row separately; returns list of ink masks."""
    from playwright.sync_api import sync_playwright
    out = []
    with sync_playwright() as p:
        b = p.chromium.launch(args=["--force-color-profile=srgb", "--font-render-hinting=none"])
        pg = b.new_page(viewport={"width": 1500, "height": 700}, device_scale_factor=1)
        pg.goto("file://" + html_path)
        pg.wait_for_timeout(200)
        try:
            pg.evaluate("document.fonts.ready")
        except Exception:
            pass
        pg.wait_for_timeout(300)
        for i in range(n):
            el = pg.query_selector(f"#r{i}")
            buf = el.screenshot(path=os.path.join(ROOT, f"work/_cmp_r{i}.png"))
            im = np.asarray(Image.open(os.path.join(ROOT, f"work/_cmp_r{i}.png")).convert("L"), dtype=float)
            out.append((im < 140).astype(np.float32))
        b.close()
    return out


def rows(ink):
    """Split a render into line bands."""
    prof = ink.sum(1) > 0
    bands = []
    s = None
    for i, v in enumerate(prof):
        if v and s is None:
            s = i
        elif not v and s is not None:
            bands.append((s, i - 1))
            s = None
    if s is not None:
        bands.append((s, len(prof) - 1))
    return bands


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=6, step=1):
    """Best mismatch fraction of a (target) vs b (candidate), over a offsets."""
    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, step):
        for dx in range(-radius, radius + 1, step):
            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
            xor = np.abs(A - B).sum()
            union = np.maximum(A, B).sum()
            v = xor / union
            if v < best[0]:
                best = (v, dx, dy)
    return best


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

    target = mock_ink([int(v) for v in args.region.split(",")])
    target = trim(target)
    cap = args.cap or target.shape[0]
    print(f"mock ink {target.shape[1]}x{target.shape[0]} (cap {cap})")

    cands = []
    for spec in args.fonts.split(","):
        parts = spec.split(":")
        fam = parts[0]
        wt = parts[1] if len(parts) > 1 else "400"
        ls = float(parts[2]) if len(parts) > 2 else 0.0
        cands.append((fam, wt, ls, spec))

    page = os.path.join(ROOT, "work/_cmp.html")
    rows_html = "\n".join(
        f'<div class="r" id="r{i}" style="font-family:\'{f}\';font-weight:{w};'
        f'letter-spacing:{ls}em">{args.text.replace(" ", "&nbsp;")}</div>'
        for i, (f, w, ls, _) in enumerate(cands))
    link = (f'<link href="{args.link}" rel="stylesheet">' if args.link else "")
    # first pass at 100px to learn each family's cap ratio, then rescale
    html = f"""<!doctype html><html><head><meta charset="utf-8">{link}
<style>
  body{{margin:0;background:#fff;color:#000}}
  .r{{font-size:100px;line-height:1.6;white-space:nowrap;display:block}}
</style></head><body>{rows_html}</body></html>"""
    open(page, "w").write(html)
    masks = render(page, len(cands))
    ratios = []
    for m in masks:
        t = trim(m)
        ratios.append(t.shape[0] / 100.0)
    rows_html = "\n".join(
        f'<div class="r" id="r{i}" style="font-family:\'{f}\';font-weight:{w};'
        f'letter-spacing:{ls}em;font-size:{cap / r:.3f}px">'
        f'{args.text.replace(" ", "&nbsp;")}</div>'
        for i, ((f, w, ls, _), r) in enumerate(zip(cands, ratios)))
    html = f"""<!doctype html><html><head><meta charset="utf-8">{link}
<style>
  body{{margin:0;background:#fff;color:#000}}
  .r{{line-height:1.5;white-space:nowrap;display:block}}
</style></head><body>{rows_html}</body></html>"""
    open(page, "w").write(html)
    masks = render(page, len(cands))
    out = []
    for sub0, (f, w, ls, spec), r in zip(masks, cands, ratios):
        sub = trim(sub0)
        v, dx, dy = score(target, sub)
        out.append((v, spec, sub.shape[1], sub.shape[0], dx, dy))
    out.sort()
    print(f"{'candidate':34s} {'inkW':>5s} {'inkH':>5s} {'mismatch':>9s}")
    for v, spec, wpx, hpx, dx, dy in out[:args.top]:
        print(f"{spec:34s} {wpx:5d} {hpx:5d} {v * 100:8.2f}%")


if __name__ == "__main__":
    main()
