#!/usr/bin/env python3
"""Render candidate faces for one mock line, aligned, and build a sheet."""
import io
import sys

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 = sys.argv[1]
MX0, MY0, MX1, MY1 = [int(v) for v in sys.argv[2].split(",")]
CROP_H = MY1 - MY0
TARGET_W = MX1 - MX0 + 1
SHADOW = sys.argv[3] if len(sys.argv) > 3 else "4px 4px 0 rgba(230,67,42,0.45)"
CANDS = [tuple(c.split(":")) for c in sys.argv[4].split(",")]
MOCK = Image.open(f"{ROOT}/mock.jpg").convert("RGB")


def solid_bbox(arr, thr=95):
    g = arr[:, :, 1]
    m = g < thr
    ys, xs = np.where(m)
    return xs.min(), ys.min(), xs.max(), ys.max()


def stem_ratio(arr, y0, y1, x0, x1):
    """Median horizontal run length of solid ink in a window."""
    g = arr[:, :, 1]
    runs = []
    for y in range(y0, y1):
        run = 0
        for x in range(x0, x1):
            if g[y, x] < 110:
                run += 1
            elif run:
                runs.append(run)
                run = 0
        if run:
            runs.append(run)
    if not runs:
        return 0
    return float(np.median([r for r in runs if r > 8] or [0]))


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;text-shadow:{SHADOW}}}</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};
        }""", [fam, wt, TEXT])
        best = None
        for scale in (0.94, 0.96, 0.98, 1.0, 1.02, 1.04, 1.06):
            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(70)
            buf = pg.screenshot()
            arr = np.array(Image.open(io.BytesIO(buf)).convert("RGB"), float)
            x0, y0, x1, y1 = solid_bbox(arr)
            # crop relative to the solid ink top-left, MOCK's solid ink top-left
            ox, oy = x0 - MX0, y0 - MY0
            crop = arr[y0:y0 + CROP_H + 6, x0:x0 + TARGET_W]
            mreg = np.array(MOCK.crop((MX0, MY0, MX0 + TARGET_W,
                                       MY0 + CROP_H + 6)), float)
            hh = min(crop.shape[0], mreg.shape[0])
            bestmae = None
            for ddy in (-3, -2, -1, 0, 1, 2, 3):
                for ddx in (-3, -2, -1, 0, 1, 2, 3):
                    yy = ddy - 0
                    cc = arr[y0 + yy:y0 + yy + hh, x0 + ddx:x0 + ddx + TARGET_W]
                    if cc.shape[0] < hh:
                        continue
                    mm = np.abs(cc - mreg[:hh]).mean()
                    if bestmae is None or mm < bestmae[0]:
                        bestmae = (mm, ddx, ddy)
            mae = bestmae[0]
            crop = arr[y0 + bestmae[2]:y0 + bestmae[2] + hh,
                       x0 + bestmae[1]:x0 + bestmae[1] + TARGET_W]
            if best is None or mae < best[0]:
                best = (mae, size, track, crop.astype(np.uint8),
                        base["cap"] * size / 100, x1 - x0)
        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} cap={best[4]:.1f} w={best[5]}")

imgs = [("mock", np.array(MOCK.crop((MX0, MY0, MX0 + TARGET_W,
                                     MY0 + CROP_H + 6))))]
imgs += [(f"{f} {w} mae={b[0]:.1f}", b[3]) for f, w, b in rows]
W = max(i.shape[1] for _, i in imgs)
H = sum(i.shape[0] for _, i in imgs)
sheet = Image.new("RGB", (W, H), (241, 228, 211))
y = 0
for label, a in imgs:
    sheet.paste(Image.fromarray(a[:CROP_H + 6]), (0, y))
    y += a.shape[0]
sheet.save(f"{ROOT}/work/fontsheet.png")
print("wrote work/fontsheet.png", sheet.size, [l for l, _ in imgs])
