#!/usr/bin/env python3
"""Measure stroke weight (stem thickness) and ink coverage of a type block.

fontspec.py normalises candidates by x-height and then ranks them on width. That
cannot see weight: a too-heavy face simply needs more negative tracking and comes
out the same width. So width tells you the family and size, and this tells you
whether the weight is right.

Two numbers, both scale-free by dividing by cap height:

  cov   ink pixels / ink-bbox area. Rises with weight, but also with tracking
        (wider spaces) and with the number of counters.
  stem  median horizontal run length in the middle 50% of the ink bbox, i.e.
        the thickness of vertical stems, excluding serifs and horizontals.
        This is the one that tracks weight.

Compare a mock against a render:

  python3 tools/stroke.py --a mock.jpg --b shots/final.png --region 60,190,900,340
  python3 tools/stroke.py --a mock.jpg --b shots/final.png --region ... --invert
"""
import argparse
import sys

import numpy as np
from PIL import Image


def load_mask(path, region, thresh, invert):
    arr = np.asarray(Image.open(path).convert("RGB"), dtype=np.float32)
    lum = arr.mean(axis=2)
    x0, y0, x1, y1 = region
    sub = lum[y0:y1 + 1, x0:x1 + 1]
    return (sub > thresh) if invert else (sub < thresh)


def stem_width(mask, band=(0.25, 0.75)):
    """Median horizontal ink run inside the middle band of the ink's bbox.

    Restricting to the middle band drops baseline/top serifs, whose runs are
    horizontal and much longer than a stem. Runs longer than half the ink height
    are horizontals or joined letters, so they are excluded rather than skewing
    the median.
    """
    ys, xs = np.where(mask)
    if len(ys) == 0:
        return None, None
    y0, y1 = int(ys.min()), int(ys.max())
    h = y1 - y0 + 1
    lo, hi = int(y0 + band[0] * h), int(y0 + band[1] * h)
    runs = []
    for y in range(lo, hi + 1):
        row = mask[y].astype(np.int8)
        if not row.any():
            continue
        d = np.diff(np.concatenate(([0], row, [0])))
        for s, e in zip(np.where(d == 1)[0], np.where(d == -1)[0]):
            L = e - s
            if 0 < L <= h * 0.5:
                runs.append(L)
    stem = float(np.median(runs)) if runs else None
    cov = float(mask[ys.min():y1 + 1, xs.min():xs.max() + 1].mean())
    return stem, cov


def report(path, region, thresh, invert):
    m = load_mask(path, region, thresh, invert)
    ys, xs = np.where(m)
    if len(ys) == 0:
        return None
    stem, cov = stem_width(m)
    return {"stem": stem, "cov": cov, "cap": int(ys.max() - ys.min() + 1),
            "w": int(xs.max() - xs.min() + 1)}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--a", required=True, help="reference image (the mockup)")
    ap.add_argument("--b", default=None, help="comparison image (the render)")
    ap.add_argument("--region", required=True, help="x0,y0,x1,y1")
    ap.add_argument("--thresh", type=float, default=None,
                    help="ink threshold on luminance (default: Otsu on the region)")
    ap.add_argument("--invert", action="store_true", help="light ink on dark ground")
    a = ap.parse_args()
    region = [int(v) for v in a.region.split(",")]

    if a.thresh is None:
        arr = np.asarray(Image.open(a.a).convert("L"), dtype=np.float32)
        sub = arr[region[1]:region[3] + 1, region[0]:region[2] + 1].ravel()
        hist, edges = np.histogram(sub, bins=64)
        centres = (edges[:-1] + edges[1:]) / 2
        # Otsu: maximise between-class variance
        best, cut = -1, centres[0]
        for i in range(1, len(hist) - 1):
            w0, w1 = hist[:i].sum(), hist[i:].sum()
            if w0 == 0 or w1 == 0:
                continue
            m0 = (hist[:i] * centres[:i]).sum() / w0
            m1 = (hist[i:] * centres[i:]).sum() / w1
            v = w0 * w1 * (m0 - m1) ** 2
            if v > best:
                best, cut = v, centres[i]
        a.thresh = float(cut)
        print(f"threshold (Otsu) = {a.thresh:.0f}")

    ra = report(a.a, region, a.thresh, a.invert)
    if ra is None:
        sys.exit("no ink found in region of --a; widen or change --thresh")
    print(f"{'':8s} {'cap':>5s} {'width':>7s} {'stem':>7s} {'cov':>7s}")
    print(f"{'mock':8s} {ra['cap']:5d} {ra['w']:7d} {ra['stem']:7.2f} {ra['cov']:7.3f}")
    if not a.b:
        print(f"\nstem/cap = {ra['stem'] / ra['cap']:.4f}")
        return

    rb = report(a.b, region, a.thresh, a.invert)
    if rb is None:
        sys.exit("no ink found in region of --b")
    print(f"{'render':8s} {rb['cap']:5d} {rb['w']:7d} {rb['stem']:7.2f} {rb['cov']:7.3f}")

    # compare stroke at equal cap height, so a size error does not read as a
    # weight error, and a weight error cannot hide behind a size error
    ma, mb = ra["stem"] / ra["cap"], rb["stem"] / rb["cap"]
    print(f"\nstem/cap  mock {ma:.4f}   render {mb:.4f}   render/mock {mb / ma:.3f}")
    d = mb / ma
    if d > 1.12:
        print(f"verdict: too heavy by ~{100 * (d - 1):.0f}% — try a lighter weight")
    elif d < 0.88:
        print(f"verdict: too light by ~{100 * (1 - d):.0f}% — try a heavier weight")
    else:
        print("verdict: weight matches within 12%")
    ca, cb = ra["cov"], rb["cov"]
    print(f"coverage mock {ca:.3f} render {cb:.3f} ({100 * (cb / ca - 1):+.0f}%)")


if __name__ == "__main__":
    main()
