#!/usr/bin/env python3
"""Measure ink boxes and colours inside a mockup.

Generic helper: give it a region and it tells you where the bright (or dark)
pixels are, which is how you recover glyph metrics and layout offsets from a
screenshot of a design.

  python3 tools/measure.py --region 0,180,1400,500 --thresh 200
  python3 tools/measure.py --region 0,180,1400,500 --thresh 200 --rows
"""
import argparse

import numpy as np
from PIL import Image


def load(path):
    return np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)


def ink_mask(arr, thresh, invert=False):
    lum = arr.mean(axis=2)
    return lum < thresh if invert else lum > thresh


def boxes(mask, min_gap=6, axis=0):
    """Contiguous runs of ink-containing lines along `axis`, allowing small gaps."""
    prof = mask.any(axis=1 - axis)
    runs, start, gap = [], None, 0
    for i, v in enumerate(prof):
        if v:
            if start is None:
                start = i
            gap = 0
        elif start is not None:
            gap += 1
            if gap > min_gap:
                runs.append((start, i - gap))
                start = None
    if start is not None:
        runs.append((start, len(prof) - 1))
    return runs


def report(arr, box, thresh, label="", invert=False):
    x0, y0, x1, y1 = box
    sub = arr[y0:y1, x0:x1]
    m = ink_mask(sub, thresh, invert)
    if not m.any():
        print(f"{label} empty")
        return
    ys, xs = np.where(m)
    print(f"{label} ink bbox x[{x0+xs.min()}..{x0+xs.max()}] "
          f"y[{y0+ys.min()}..{y0+ys.max()}] "
          f"w={xs.max()-xs.min()+1} h={ys.max()-ys.min()+1}")
    return (x0 + xs.min(), y0 + ys.min(), x0 + xs.max(), y0 + ys.max())


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--img", default="mock.jpg")
    ap.add_argument("--region", default="0,0,100000,100000")
    ap.add_argument("--thresh", type=float, default=200)
    ap.add_argument("--rows", action="store_true", help="split into text lines")
    ap.add_argument("--cols", action="store_true", help="split into columns")
    ap.add_argument("--min-gap", type=int, default=4)
    ap.add_argument("--color", action="store_true", help="sample ink colour")
    ap.add_argument("--invert", action="store_true",
                    help="ink is darker than the background (dark on light)")
    a = ap.parse_args()

    arr = load(a.img)
    x0, y0, x1, y1 = [int(v) for v in a.region.split(",")]
    x1 = min(x1, arr.shape[1])
    y1 = min(y1, arr.shape[0])
    sub = arr[y0:y1, x0:x1]
    m = ink_mask(sub, a.thresh, a.invert)

    print(f"image {arr.shape[1]}x{arr.shape[0]}  region {x0},{y0} -> {x1},{y1}")
    report(arr, (x0, y0, x1, y1), a.thresh, "region", a.invert)

    if a.cols:
        for s, e in boxes(m, a.min_gap, axis=1):
            report(arr, (x0 + s, y0, x0 + e + 1, y1), a.thresh,
                   f"  col {x0+s}..{x0+e}", a.invert)
    if a.rows:
        for s, e in boxes(m, a.min_gap, axis=0):
            report(arr, (x0, y0 + s, x1, y0 + e + 1), a.thresh,
                   f"  row {y0+s}..{y0+e}", a.invert)

    if a.color:
        px = sub[m]
        print("ink mean #%02x%02x%02x  p95 #%02x%02x%02x   bg median #%02x%02x%02x"
              % (tuple(px.mean(axis=0).astype(int))
                 + tuple(np.percentile(px, 95, axis=0).astype(int))
                 + tuple(np.median(sub[~m], axis=0).astype(int))))


if __name__ == "__main__":
    main()
