#!/usr/bin/env python3
"""Identify a typeface by comparing candidates against a mockup's ink.

Fonts are normalised by *x-height*, never by font-size. Matching by font-size is
meaningless across families; matching x-height puts every candidate's letterforms
on a common footing so the remaining differences (shape, width, tracking) are the
things you actually judge.

  python3 tools/fontspec.py --text "Deliver vetted restaurants," \
      --mock-line 59,202,1361,284 --sheet work/specimen.png

Outputs a table of implied font-size / tracking plus a contact sheet: the mockup's
line on top and each candidate below it, aligned on the left edge and baseline.
"""
import argparse
import json
import os

import sys

import numpy as np
from PIL import Image

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from stroke import stem_width  # noqa: E402  (sibling tool)

ROOT = (os.environ.get("MOCKUP_ROOT")
        or os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def split_spec(s):
    """`Family`, `Family:600`, or `Family:600:italic`."""
    bits = [b.strip() for b in s.split(":")]
    fam = bits[0]
    wt = bits[1] if len(bits) > 1 and bits[1] else "400"
    ital = "1" if len(bits) > 2 and bits[2].lower() in ("i", "italic") else "0"
    return fam, wt, ital


def css_url(specs):
    """One family param per family, with its (ital, wght) tuples merged.

    Google rejects the same family twice and needs the tuples sorted, so group
    rather than emitting one param per candidate.
    """
    by_fam = {}
    for s in specs:
        fam, wt, ital = split_spec(s)
        by_fam.setdefault(fam, set()).add((ital, wt))
    parts = []
    for fam, tuples in by_fam.items():
        t = sorted(tuples, key=lambda q: (int(q[0]), float(q[1])))
        parts.append("family=" + fam.replace(" ", "+") +
                     ":ital,wght@" + ";".join(i + "," + w for i, w in t))
    return ("https://fonts.googleapis.com/css2?"
            + "&".join(parts) + "&display=block")


class Probe:
    """One page holding every candidate, so fonts load once."""

    def __init__(self, specs):
        from playwright.sync_api import sync_playwright
        self._pw = sync_playwright().start()
        self.b = self._pw.chromium.launch(
            channel="chrome",
            args=["--font-render-hinting=none", "--force-color-profile=srgb"])
        self.pg = self.b.new_page(viewport={"width": 2400, "height": 1200},
                                  device_scale_factor=1)
        rows = "".join(
            f'<div class="row" id="r{i}" data-f="{split_spec(s)[0]}" '
            f'data-w="{split_spec(s)[1]}" data-i="{split_spec(s)[2]}">'
            f'<span class="t"></span></div>'
            for i, s in enumerate(specs))
        html = f"""<!doctype html><html><head><meta charset="utf-8">
<link rel="stylesheet" href="{css_url(specs)}">
<style>
 html,body{{margin:0;background:transparent}}
 .row{{position:relative;white-space:nowrap;display:inline-block;line-height:1}}
 .t{{display:inline-block;line-height:1;color:#f4eddb;padding:0}}
</style></head><body>{rows}</body></html>"""
        tmp = os.path.join(ROOT, "work", "_fontprobe.html")
        os.makedirs(os.path.dirname(tmp), exist_ok=True)
        open(tmp, "w").write(html)
        self.pg.goto("file://" + tmp)
        try:
            self.pg.wait_for_function(
                "document.fonts.status === 'loaded'", timeout=120000)
        except Exception:
            pass
        self.pg.wait_for_timeout(2000)

    def metrics(self, specs, text):
        js = """async (specs) => {
          for (const s of specs) {
            await document.fonts.load(`${s.s} ${s.w} 100px "${s.f}"`);
          }
          await document.fonts.ready;
          return specs.map(s => {
          const cv = document.createElement('canvas');
          const ctx = cv.getContext('2d');
          const ref = 400;
          ctx.font = `${s.s} ${s.w} ${ref}px "${s.f}"`;
          const m = t => { const x = ctx.measureText(t);
            return {l:x.actualBoundingBoxLeft, r:x.actualBoundingBoxRight,
                    a:x.actualBoundingBoxAscent, d:x.actualBoundingBoxDescent,
                    w:x.width}; };
          return {f:s.f, w:s.w, s:s.s, ref, xh:m('x').a, cap:m('H').a,
                  asc:m('d').a, desc:m('p').d, str:m(s.text)};
        });
        }"""
        return self.pg.evaluate(js, [
            {"f": split_spec(s)[0], "w": split_spec(s)[1],
             "s": "italic" if split_spec(s)[2] == "1" else "normal",
             "text": text} for s in specs])

    def ink(self, idx, text, family, weight, size, tracking):
        self.pg.evaluate(
            """([i, text, size, tracking]) => {
              const row = document.getElementById('r'+i);
              const t = row.querySelector('.t');
              t.textContent = text;
              t.style.fontSize = size + 'px';
              t.style.letterSpacing = tracking + 'em';
              t.style.fontFamily = `"${row.dataset.f}"`;
              t.style.fontWeight = row.dataset.w;
              t.style.fontStyle = row.dataset.i === '1' ? 'italic' : 'normal';
            }""", [idx, text, size, tracking])
        el = self.pg.query_selector(f"#r{idx}")
        buf = el.screenshot(omit_background=True)
        import io
        return Image.open(io.BytesIO(buf)).convert("RGBA")

    def close(self):
        self.b.close()
        self._pw.stop()


def ink_bbox(im_rgba):
    a = np.asarray(im_rgba)
    m = a[..., 3] > 40
    ys, xs = np.where(m)
    if len(ys) == 0:
        return None
    return xs.min(), ys.min(), xs.max(), ys.max()


def mock_line_metrics(path, line, invert=None):
    """Ink bbox of the mockup's line, with the polarity detected not assumed.

    The old fixed `lum > 150` tested for light ink. On a cream mockup that selects
    the *background*, so the "ink" was just the crop box, and passing a tight crop
    made it look correct. Detect instead: whatever is the minority class is ink.
    """
    x0, y0, x1, y1 = [int(v) for v in line.split(",")]
    arr = np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)
    lum = arr.mean(axis=2)
    sub = lum[y0:y1 + 1, x0:x1 + 1]
    mid = (np.percentile(sub, 2) + np.percentile(sub, 98)) / 2
    dark = sub < mid
    if invert is None:
        invert = bool(dark.mean() > 0.5)  # ink is the minority class
    m = dark if not invert else ~dark
    ys, xs = np.where(m)
    return (x0 + xs.min(), y0 + ys.min(), x0 + xs.max(), y0 + ys.max()), arr, m


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--text", required=True)
    ap.add_argument("--mock-line", required=True, help="x0,y0,x1,y1 (generous box)")
    ap.add_argument("--mock-img", default="mock.jpg")
    ap.add_argument("--fonts", required=True, help="comma separated fam:weight")
    ap.add_argument("--xh", type=float, default=None,
                    help="mock x-height in px; default: derive from --xh-glyph")
    ap.add_argument("--cap", type=float, default=None,
                    help="mock cap-height in px; derive size from cap instead of x-height")
    ap.add_argument("--xh-glyph", default=None,
                    help="x0,y0,x1,y1 of a lowercase-only run in the mock")
    ap.add_argument("--weights", default=None,
                    help="comma separated weights to sweep for every family given "
                         "without an explicit weight, e.g. 400,500,700,800")
    ap.add_argument("--invert", action="store_true", default=None,
                    help="ink is light on a dark ground (default: detected)")
    ap.add_argument("--sheet", default=None)
    ap.add_argument("--json", default=None)
    ap.add_argument("--overlay", default=None,
                    help="directory for per-candidate overlays against the mock")
    a = ap.parse_args()

    specs = [s.strip() for s in a.fonts.split(",") if s.strip()]
    if a.weights:
        wl = [w.strip() for w in a.weights.split(",") if w.strip()]
        swept = []
        for sp in specs:
            bits = sp.split(":")
            if len(bits) > 1 and bits[1].strip():
                swept.append(sp)
                continue
            tail = (":" + bits[2]) if len(bits) > 2 else ""
            swept += [f"{bits[0]}:{w}{tail}" for w in wl]
        specs = swept
    mbox, arr, mmask = mock_line_metrics(os.path.join(ROOT, a.mock_img), a.mock_line, a.invert)
    mock_w = mbox[2] - mbox[0] + 1
    mock_h = mbox[3] - mbox[1] + 1

    mock_xh = a.xh
    if mock_xh is None and a.xh_glyph:
        gx0, gy0, gx1, gy1 = [int(v) for v in a.xh_glyph.split(",")]
        sub = arr[gy0:gy1 + 1, gx0:gx1 + 1].mean(axis=2) > 150
        ys, xs = np.where(sub)
        mock_xh = float(ys.max() - ys.min() + 1)
    if mock_xh is None and a.cap is None:
        raise SystemExit("need --xh, --cap or --xh-glyph")
    if mock_xh is None:
        mock_xh = -1.0

    mock_stem, _ = stem_width(mmask)
    mock_stem_cap = (mock_stem / mock_h) if mock_stem else None
    print(f"mock: ink {mock_w}x{mock_h} from {mbox}  x-height {mock_xh} cap {a.cap}"
          + (f"  stem {mock_stem:.2f} stem/ink {mock_stem_cap:.4f}" if mock_stem else ""))

    probe = Probe(specs)
    met = probe.metrics(specs, a.text)

    rows, table = [], []
    for i, (s, mt) in enumerate(zip(specs, met)):
        fam, wt, ital = split_spec(s)
        if a.cap is not None:
            size = a.cap / (mt["cap"] / mt["ref"])
        else:
            size = mock_xh / (mt["xh"] / mt["ref"])
        # natural ink width of the string at that size, before tracking
        nat = (mt["str"]["l"] + mt["str"]["r"]) / mt["ref"]
        natural_px = nat * size
        need = (mock_w - natural_px) / max(1, len(a.text) - 1) / size
        im = probe.ink(i, a.text, fam, wt, size, 0.0)
        bb = ink_bbox(im)
        if bb is None:
            continue
        crop = im.crop((bb[0], bb[1], bb[2] + 1, bb[3] + 1))
        cmask = np.asarray(im)[..., 3] > 40
        cstem, _ = stem_width(cmask[bb[1]:bb[3] + 1, bb[0]:bb[2] + 1])
        c_ratio = (cstem / crop.height) if cstem else None
        d_stem = (c_ratio / mock_stem_cap) if (c_ratio and mock_stem_cap) else 0.0
        style = " italic" if ital == "1" else ""
        rows.append(dict(label=f"{fam} {wt}{style}", img=crop,
                         xh_ratio=float(mt["xh"] / mt["ref"]),
                         size=float(size), w=int(crop.width), h=int(crop.height),
                         pitch=float(crop.height / max(1.0, mock_xh)),
                         d_width=int(crop.width - mock_w),
                         cap=float(mt["cap"] / mt["ref"] * size),
                         stem=float(cstem or 0.0), d_stem=float(d_stem),
                         need_tracking=need))
        table.append(dict(family=fam, weight=wt, style=style.strip() or "roman",
                          size=round(float(size), 2),
                          ink_w=int(crop.width),
                          d_width=int(crop.width - mock_w),
                          xh_per_cap=round(float(mt["xh"] / mt["cap"]), 4),
                          tracking_to_fit_em=round(float(need), 4),
                          stem=round(float(cstem or 0.0), 2),
                          stem_vs_mock=round(float(d_stem), 3)))
    probe.close()

    print(f"{'family':24s} {'wt':>4s} {'size':>7s} {'inkW':>6s} {'dW':>6s} "
          f"{'xh/cap':>7s} {'track.em':>9s} {'stem':>6s} {'wt x':>6s}")
    for t in table:
        print(f"{t['family']:24s} {t['weight']:>4s} {t['size']:7.2f} "
              f"{t['ink_w']:6d} {t['d_width']:+6d} {t['xh_per_cap']:7.4f} "
              f"{t['tracking_to_fit_em']:+9.4f} {t['stem']:6.2f} {t['stem_vs_mock']:6.2f}")
    if mock_stem_cap:
        print(f"\nmock stem/cap = {mock_stem_cap:.4f}; 'wt x' is each candidate's "
              f"stem/cap divided by it (>1.15 too heavy, <0.87 too light)")

    if a.json:
        open(os.path.join(ROOT, a.json), "w").write(json.dumps(table, indent=1))

    if a.overlay:
        os.makedirs(os.path.join(ROOT, a.overlay), exist_ok=True)
        mock_im = Image.open(os.path.join(ROOT, a.mock_img)).convert("RGB").crop(
            (mbox[0], mbox[1], mbox[2] + 1, mbox[3] + 1))
        mg = np.asarray(mock_im.convert("L"), dtype=np.float32)
        mg = np.clip(mg / max(1.0, np.percentile(mg, 99)), 0, 1)
        for i, (sp, mt, tb) in enumerate(zip(specs, met, table)):
            fam, wt, ital = split_spec(sp)
            im = probe2_ink(ROOT, a, fam, wt, mt, tb["size"], tb["tracking_to_fit_em"],
                            mg, mbox, mock_im, i, ital)
            print("overlay", fam, wt, im)

    if a.sheet:
        pad, gap = 44, 16
        top_mock = Image.open(os.path.join(ROOT, a.mock_img)).convert("RGB").crop(
            (mbox[0], mbox[1], mbox[2] + 1, mbox[3] + 1))
        W = max(top_mock.width, max(r["w"] for r in rows)) + pad + 260
        H = top_mock.height + sum(r["h"] + gap for r in rows) + gap * 2 + 24
        sheet = Image.new("RGB", (W, H), (11, 47, 46))
        y = gap
        sheet.paste(top_mock, (pad, y))
        _tag(sheet, "MOCK", (8, y))
        y += top_mock.height + gap
        for r in rows:
            sheet.paste(r["img"], (pad, y), r["img"])
            _tag(sheet, r["label"], (8, y))
            _tag(sheet, f"{r['d_width']:+d}px", (W - 96, y))
            y += r["h"] + gap
        sheet.save(os.path.join(ROOT, a.sheet))
        print("wrote", a.sheet, sheet.size)


def probe2_ink(root, a, fam, wt, mt, size, tracking, mg, mbox, mock_im, idx,
               ital="0"):
    """Re-render a candidate with fitted tracking and composite it over the mock."""
    probe = Probe([f"{fam}:{wt}" + (":italic" if ital == "1" else "")])
    im = probe.ink(0, a.text, fam, wt, size, tracking)
    probe.close()
    bb = ink_bbox(im)
    crop = im.crop((bb[0], bb[1], bb[2] + 1, bb[3] + 1))
    a_ = np.asarray(crop)
    ink = a_[..., 3].astype(np.float32) / 255.0
    H = max(mg.shape[0], ink.shape[0])
    W = max(mg.shape[1], ink.shape[1])
    out = np.zeros((H, W, 3), dtype=np.float32)
    out[:mg.shape[0], :mg.shape[1], 0] = mg
    out[:ink.shape[0], :ink.shape[1], 1] = ink
    img = Image.fromarray((np.clip(out, 0, 1) * 255).astype(np.uint8))
    name = (f"{fam.replace(' ', '_')}_{wt}"
            + ("_i" if ital == "1" else "") + "_overlay.png")
    img.save(os.path.join(root, a.overlay, name))
    return name


def _tag(img, text, xy):
    from PIL import ImageDraw
    d = ImageDraw.Draw(img)
    d.text(xy, text, fill=(120, 200, 190))


if __name__ == "__main__":
    main()
