#!/usr/bin/env python3
"""Diff landmark ink-boxes between the mockup and a render.

Eyeballing a side-by-side tells you something is off. This tells you *how much*
and *which way*, so corrections are arithmetic instead of guesswork.

Regions are generous boxes; each one should contain exactly one element. Every
region is measured the same way on both images, so the only difference between
the two numbers is the design.

  python3 tools/landmarks.py --render shots/it03.png
  python3 tools/landmarks.py --render shots/it03.png --only headline
"""
import argparse
import json
import os

import numpy as np
from PIL import Image

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

# name: [x0, y0, x1, y1, threshold, "bright"|"dark"]
# A starting set for a hero-shaped mockup. Re-derive these per design: each box
# must contain exactly one element and must not clip it, or the deltas it reports
# are fiction. Check for ink sitting on a region edge before believing a number.
DEFAULT_REGIONS = {
    "logo":        [10, 10, 340, 88, 120, "bright"],
    "nav":         [600, 10, 1305, 90, 150, "bright"],
    "btn:top":     [1305, 6, 1530, 92, 150, "bright"],
    "eyebrow":     [20, 132, 560, 190, 130, "bright"],
    "district":    [600, 108, 1180, 200, 130, "bright"],
    "headline:1":  [20, 186, 1460, 298, 170, "bright"],
    "headline:2":  [20, 300, 1460, 398, 170, "bright"],
    "headline:3":  [20, 400, 780, 512, 170, "bright"],
    "sub":         [20, 529, 1240, 548, 150, "bright"],
    "btn:cta":     [20, 576, 320, 674, 140, "bright"],
    "link":        [322, 590, 520, 668, 140, "bright"],
    "stats":       [20, 708, 470, 840, 150, "bright"],
    "pin:gct":     [1160, 436, 1206, 500, 105, "bright"],
    "pin:bryant":  [800, 580, 900, 664, 105, "bright"],
    "pin:esb":     [800, 756, 900, 854, 105, "bright"],
}


def ink_box(path, region):
    x0, y0, x1, y1, thr, mode = region
    arr = np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)
    lum = arr.mean(axis=2)
    sub = lum[y0:y1, x0:x1]
    m = (sub > thr) if mode == "bright" else (sub < thr)
    ys, xs = np.where(m)
    if len(ys) == 0:
        return None
    return (x0 + int(xs.min()), y0 + int(ys.min()),
            x0 + int(xs.max()), y0 + int(ys.max()))


def rule_y(path, x=700, y0=80, y1=120):
    """Find the header rule: the locally brightest row in a dark column band."""
    arr = np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)
    band = arr[y0:y1, x - 60:x + 60].mean(axis=(1, 2))
    i = int(np.argmax(band))
    return y0 + i, float(band[i])


def col_runs(path, region, min_gap=6):
    x0, y0, x1, y1, thr, mode = region
    arr = np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)
    sub = arr[y0:y1, x0:x1].mean(axis=2)
    m = (sub > thr) if mode == "bright" else (sub < thr)
    prof = m.sum(axis=0)
    runs, start, gap = [], None, 0
    for i, v in enumerate(prof):
        if v > 0:
            if start is None:
                start = i
            gap = 0
        elif start is not None:
            gap += 1
            if gap > min_gap:
                runs.append((x0 + start, x0 + i - gap))
                start = None
    if start is not None:
        runs.append((x0 + start, x0 + len(prof) - 1))
    return runs


def compare_cols(mock, ren, region, min_gap):
    a = col_runs(mock, region, min_gap)
    b = col_runs(ren, region, min_gap)
    print(f"  mock   {len(a):2d} runs: " + " ".join(f"{s}-{e}" for s, e in a))
    print(f"  render {len(b):2d} runs: " + " ".join(f"{s}-{e}" for s, e in b))
    n = min(len(a), len(b))
    if n:
        wid = " ".join(f"{((b[i][1]-b[i][0])-(a[i][1]-a[i][0])):+d}" for i in range(n))
        left = " ".join(f"{b[i][0]-a[i][0]:+d}" for i in range(n))
        print(f"  d width {wid}")
        print(f"  d left  {left}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--render", required=True)
    ap.add_argument("--mock", default="mock.jpg")
    ap.add_argument("--regions", default=None, help="json file overriding regions")
    ap.add_argument("--only", default=None)
    ap.add_argument("--cols", default=None,
                    help="comma separated region names to split into columns")
    ap.add_argument("--min-gap", type=int, default=6)
    a = ap.parse_args()

    regions = DEFAULT_REGIONS
    if a.regions:
        regions = json.load(open(os.path.join(ROOT, a.regions)))

    mock = os.path.join(ROOT, a.mock)
    ren = os.path.join(ROOT, a.render)

    print(f"{'landmark':12s} {'mock x0,y0,x1,y1':26s} {'render':26s} "
          f"{'dL':>4s} {'dT':>4s} {'dW':>4s} {'dH':>4s}")
    worst = []
    for name, reg in regions.items():
        if a.only and a.only not in name:
            continue
        bm = ink_box(mock, reg)
        br = ink_box(ren, reg)
        if bm is None or br is None:
            print(f"{name:12s} {'MISSING mock' if bm is None else 'ok':26s} "
                  f"{'MISSING render' if br is None else 'ok'}")
            continue
        dL, dT = br[0] - bm[0], br[1] - bm[1]
        dW = (br[2] - br[0]) - (bm[2] - bm[0])
        dH = (br[3] - br[1]) - (bm[3] - bm[1])
        flag = "  <<<" if max(abs(dL), abs(dT), abs(dW), abs(dH)) >= 4 else ""
        print(f"{name:12s} {str(bm):26s} {str(br):26s} "
              f"{dL:+4d} {dT:+4d} {dW:+4d} {dH:+4d}{flag}")
        worst.append((max(abs(dL), abs(dT), abs(dW), abs(dH)), name))

    ym, vm = rule_y(mock)
    yr, vr = rule_y(ren)
    print(f"{'rule':12s} y={ym}                y={yr}                 dY {yr-ym:+d}")

    if a.cols:
        for name in a.cols.split(","):
            reg = regions[name]
            print(f"\n[{name}]")
            compare_cols(mock, ren, reg, a.min_gap)

    worst.sort(reverse=True)
    print("\nworst:", ", ".join(f"{n}({d})" for d, n in worst[:5]))


if __name__ == "__main__":
    main()
