"""Crown Landmark silhouette review tool: model renders vs R06 reference imagery.

Usage:
    python compare.py <tag> [--out DIR] [--only PAIR[,PAIR...]]
      <tag>   e.g. C03_r1  -> reads CrownLandmark/out/assembly/<tag>_{front,rear,left,right,elevated,elevated_rear}.png
      --out   output folder (default CrownLandmark/out/compare/<tag>/)
      --only  restrict to pair ids (see PAIRS below), e.g. --only front,left_b02
    Needs numpy + pillow only (no scipy / opencv). Deterministic: no randomness, fixed thresholds.

What it does, per (model render, reference) pair:
  1. SEGMENT the building from the flat background. The background colour is estimated per image row from
     the outer 8 px strips at the left/right image edges (references have a soft vertical gradient; models a
     flat colour), interpolated across the row. A pixel is "building" when its colour distance from that
     background exceeds a per-image threshold (THRESH, default ref 17 / model 9, overridable per pair).
     Soft cast shadows below the base plate are rejected (hue test). Cleaning (numpy + PIL rank filters): closing (5 px), opening (3 px),
     references only: vertical opening (removes <9 px thin horizontal ground-line artefacts), keep the largest connected blob,
     fill every enclosed hole (glass that happens to match the background, small see-through gaps).
  2. NORMALISE: crop each silhouette to its bounding box, scale uniformly to the same height (900 px) and
     centre it horizontally on its bounding box, in a 760 x 980 canvas.
  3. SCORE: IoU, width profile at 12 equally spaced heights (top->bottom, band centres), reported as
     fraction of silhouette height for both "span" (right edge - left edge) and "cover" (sum of filled
     pixels, so gaps between ribs/petals count as empty) plus the model-minus-reference difference, and
     the top-5 height bands where the model is too wide / too narrow (relative span error >= 8 percent,
     adjacent bands of the same sign merged, up to 3 bands (~30 m) per region, ranked by area error). RAW numbers (no normalisation: IoU in
     the 1024x1536 frame, bbox size and offset as fractions of the frame) are reported next to them.
  4. WRITE a sheet per pair: reference | model | overlay (red = reference only, blue = model only,
     purple = both) to <out>/<pair>.png, plus scores.json and SUMMARY.md.

IMPORTANT - approximate guide, not pass/fail. References are perspective AI concept renders (the base
plate is seen from above, verticals converge, ribs/petals are artistic); the model renders are
orthographic (front/rear/left/right) or a different perspective camera (elevated). Even a perfect
model will not reach IoU 1.0. Height-normalised numbers remove scale/framing differences but not
perspective. Use the deltas as direction ("too thin around mid height"), not as grades. Reference
background gradient, soft shadows, and ivory areas close to the background colour can bite into the
reference mask; always look at the sheets.

Pairs (id: model view, reference file):
    front, front_master, rear, rear_b02, left_b02, left_obl, right_b02, right_obl, elevated_05,
    elevated_08, elevated_rear_06.  The *_b02 references are panels cropped out of the B02 elevations
    board (re-scaled to 1536 px tall); left/right panels are the closest thing to a true side elevation.
"""
import sys, os, json, argparse
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, ".."))
REFS = os.path.join(ROOT, "refs")
ASM = os.path.join(ROOT, "out", "assembly")

P = "PI-BLD-0001-V01_CrownLandmark_EXT_R06_"
IV = os.path.join(REFS, "03_IndividualViews", P)
B02 = os.path.join(REFS, "02_OverviewBoards", P + "B02_Elevations_Corrected.jpeg")
MASTER = os.path.join(REFS, "01_Master", P + "Master_Tall.jpeg")
# B02 panel boxes (x0, y0, x1, y1) inside the 1536x768 board, inset to avoid the panel frame lines
B02_BOX = {"front": (24, 62, 394, 696), "rear": (412, 62, 764, 696),
           "left": (780, 62, 1142, 696), "right": (1158, 62, 1510, 696)}

# id -> (model view suffix, reference path, B02 panel or None, primary view?, orthographic model?)
PAIRS = {
    "front":            ("front",        IV + "01_Front.png",          None,    True,  True),
    "front_master":     ("front",        MASTER,                       None,    False, True),
    "rear":             ("rear",         IV + "02_Rear.png",           None,    True,  True),
    "rear_b02":         ("rear",         B02,                          "rear",  False, True),
    "left_b02":         ("left",         B02,                          "left",  True,  True),
    "left_obl":         ("left",         IV + "03_LeftOblique.png",    None,    False, True),
    "right_b02":        ("right",        B02,                          "right", True,  True),
    "right_obl":        ("right",        IV + "04_RightOblique.png",   None,    False, True),
    "elevated_05":      ("elevated",     IV + "05_FrontElevated.png",  None,    True,  False),
    "elevated_08":      ("elevated",     IV + "08_ThreeQuarter.png",   None,    False, False),
    "elevated_rear_06": ("elevated_rear", IV + "06_RearElevated.png",  None,    False, False),
}

# colour-distance thresholds (Euclidean RGB). Per-pair override: THRESH_OVERRIDE[pair] = (ref_thr, model_thr)
REF_THR, MODEL_THR = 17.0, 9.0
PERP_THR, BRIGHT_THR = 9.0, 45.0   # shadow rejection (see segment())
THRESH_OVERRIDE = {}

FRAME_W, FRAME_H = 1024, 1536
NORM_H, CANVAS_W, CANVAS_H, MARGIN_TOP = 900, 760, 980, 40
NPROF = 12            # width-profile samples
NBANDS = 24           # bands for region finding
MAX_MERGE = 3         # max adjacent bands merged into one region (3 bands = 12.5 percent of height)
REL_TOL = 0.08        # relative span error below this is ignored
MODEL_HEIGHT_M = 240.0


# ----------------------------------------------------------------------------- image helpers
def load_frame(path, box=None):
    """Load an image (optionally crop a B02 panel) and return a 1024x1536 RGB uint8 array.
    Panels / other sizes are scaled to 1536 px tall and padded sideways by edge replication."""
    im = Image.open(path).convert("RGB")
    if box:
        im = im.crop(box)
    if im.size != (FRAME_W, FRAME_H):
        s = FRAME_H / im.size[1]
        im = im.resize((max(1, round(im.size[0] * s)), FRAME_H), Image.LANCZOS)
    a = np.asarray(im)
    w = a.shape[1]
    if w < FRAME_W:
        l = (FRAME_W - w) // 2
        a = np.pad(a, ((0, 0), (l, FRAME_W - w - l), (0, 0)), mode="edge")
    elif w > FRAME_W:
        l = (w - FRAME_W) // 2
        a = a[:, l:l + FRAME_W]
    return np.ascontiguousarray(a)


def bg_estimate(a, strip=8):
    """Per-row background colour from left/right edge strips, linearly interpolated across x."""
    f = a.astype(np.float32)
    L = np.median(f[:, :strip], axis=1)            # (H,3)
    R = np.median(f[:, -strip:], axis=1)
    k = 9                                           # smooth along y
    pad = lambda v: np.pad(v, ((k, k), (0, 0)), mode="edge")
    sm = lambda v: np.stack([np.convolve(pad(v)[:, c], np.ones(2 * k + 1) / (2 * k + 1), "valid") for c in range(3)], 1)
    L, R = sm(L), sm(R)
    t = np.linspace(0, 1, a.shape[1], dtype=np.float32)[None, :, None]
    return L[:, None, :] * (1 - t) + R[:, None, :] * t


def rank_filter(mask, size, mode):
    im = Image.fromarray((mask * 255).astype(np.uint8))
    im = im.filter(ImageFilter.MaxFilter(size) if mode == "max" else ImageFilter.MinFilter(size))
    return np.asarray(im) > 127


def close_open(mask):
    m = rank_filter(rank_filter(mask, 5, "max"), 5, "min")     # closing
    return rank_filter(rank_filter(m, 3, "min"), 3, "max")      # opening


def _cells(mask, s=4):
    h, w = mask.shape
    h4, w4 = h // s * s, w // s * s
    return mask[:h4, :w4].reshape(h4 // s, s, w4 // s, s).any(axis=(1, 3))


def _label_q(q):
    """Components of a small bool array via PIL floodfill. Returns list of bool arrays."""
    img = Image.fromarray((q * 255).astype(np.uint8)).copy()
    out = []
    while True:
        idx = np.flatnonzero(np.asarray(img) == 255)
        if idx.size == 0:
            break
        y, x = divmod(int(idx[0]), q.shape[1])
        ImageDraw.floodfill(img, (x, y), 128)
        arr = np.asarray(img) == 128
        out.append(arr)
        img = Image.fromarray(np.where(arr, 0, np.asarray(img)).astype(np.uint8)).copy()
    return out


def largest_blob_and_fill(mask, s=4):
    """Keep the largest connected blob, then fill all enclosed holes (computed on a 4x coarser grid)."""
    q = _cells(mask, s)
    comps = _label_q(q)
    if not comps:
        return mask
    best = max(comps, key=lambda c: c.sum())
    up = np.kron(best, np.ones((s, s), dtype=bool))
    full = np.zeros_like(mask)
    full[:up.shape[0], :up.shape[1]] = up
    mask = mask & full
    # holes: coarse background cells not reachable from the border
    q2 = _cells(mask, s)
    padq = np.pad(~q2, 1, constant_values=True)          # True = background cell, border all bg
    img = Image.fromarray((padq * 255).astype(np.uint8)).copy()
    ImageDraw.floodfill(img, (0, 0), 128)
    reach = (np.asarray(img) == 128)[1:-1, 1:-1]
    holes = (~q2) & ~reach
    hu = np.kron(holes, np.ones((s, s), dtype=bool))
    hf = np.zeros_like(mask)
    hf[:hu.shape[0], :hu.shape[1]] = hu
    return mask | hf


def vertical_open(mask, k=4):
    """Remove features thinner than 2k+1 px vertically (thin horizontal ground-line artefacts in the AI refs)."""
    h = mask.shape[0]
    er = mask.copy()
    for d in range(1, k + 1):
        er[d:] &= mask[:-d]
        er[:-d] &= mask[d:]
    out = er.copy()
    for d in range(1, k + 1):
        out[d:] |= er[:-d]
        out[:-d] |= er[d:]
    return out & mask


def segment(a, thr, is_ref=False):
    """Building = colour distance from the row background > thr, but soft cast shadows (the background
    colour merely darkened) are rejected: the difference vector is split into a part along the background
    colour (brightness change) and a perpendicular part (hue/chroma change). A pixel counts as building if
    the perpendicular part > PERP_THR or the brightness change is large (> BRIGHT_THR)."""
    bg = bg_estimate(a)
    diff = a.astype(np.float32) - bg
    u = bg / np.linalg.norm(bg, axis=2, keepdims=True)
    along = (diff * u).sum(axis=2)
    perp = np.linalg.norm(diff - along[..., None] * u, axis=2)
    d = np.sqrt(along ** 2 + perp ** 2)
    m = (d > thr) & ((perp > PERP_THR) | (np.abs(along) > BRIGHT_THR))
    m[:, :6] = False
    m[:, -6:] = False
    m = close_open(m)
    if is_ref:
        m = vertical_open(m)
    return largest_blob_and_fill(m)


def bbox(mask):
    ys, xs = np.where(mask)
    return int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1


def normalise(a, mask):
    """Crop to bbox, scale to NORM_H tall, centre in the canvas. Returns (rgb, mask, scale)."""
    x0, y0, x1, y1 = bbox(mask)
    s = NORM_H / (y1 - y0)
    w = max(1, round((x1 - x0) * s))
    im = Image.fromarray(a).crop((x0, y0, x1, y1)).resize((w, NORM_H), Image.LANCZOS)
    mk = Image.fromarray((mask * 255).astype(np.uint8)).crop((x0, y0, x1, y1)).resize((w, NORM_H), Image.BILINEAR)
    rgb = np.full((CANVAS_H, CANVAS_W, 3), 0, np.uint8)
    m = np.zeros((CANVAS_H, CANVAS_W), bool)
    ox = (CANVAS_W - w) // 2
    sx0, dx0 = max(0, -ox), max(0, ox)
    n = min(w - sx0, CANVAS_W - dx0)
    rgb[MARGIN_TOP:MARGIN_TOP + NORM_H, dx0:dx0 + n] = np.asarray(im)[:, sx0:sx0 + n]
    m[MARGIN_TOP:MARGIN_TOP + NORM_H, dx0:dx0 + n] = (np.asarray(mk) > 127)[:, sx0:sx0 + n]
    return rgb, m, s


# ----------------------------------------------------------------------------- metrics
def iou(a, b):
    u = (a | b).sum()
    return float((a & b).sum() / u) if u else 0.0


def profile(mask, y_top, height, n=NPROF, denom=None):
    """Span and cover width (fraction of `denom`, default `height`) at n band centres, top->bottom."""
    denom = denom or height
    span, cover = [], []
    for i in range(n):
        y = int(round(y_top + (i + 0.5) / n * height))
        row = mask[min(y, mask.shape[0] - 1)]
        xs = np.flatnonzero(row)
        span.append(float((xs.max() - xs.min() + 1) / denom) if xs.size else 0.0)
        cover.append(float(row.sum() / denom))
    return span, cover


def edges(mask, y):
    xs = np.flatnonzero(mask[y])
    return (int(xs.min()), int(xs.max())) if xs.size else (None, None)


def height_label(frac_from_top, ortho):
    pct = round((1 - frac_from_top) * 100)
    if ortho:
        return "z~%d m (%d%% of height)" % (round((1 - frac_from_top) * MODEL_HEIGHT_M), pct)
    return "%d%% of the way up" % pct


def regions(ref_m, mod_m, ortho, top=5):
    """Height bands where model span differs from reference span; merged same-sign neighbours; top N."""
    bands = []
    for i in range(NBANDS):
        y0 = MARGIN_TOP + int(i * NORM_H / NBANDS)
        y1 = MARGIN_TOP + int((i + 1) * NORM_H / NBANDS)
        ys = np.arange(y0, y1, 2)
        def avg(mask, fn):
            return float(np.mean([fn(mask, y) for y in ys]))
        def span(mask, y):
            xs = np.flatnonzero(mask[y]); return (xs.max() - xs.min() + 1) if xs.size else 0
        def cov(mask, y): return mask[y].sum()
        def left(mask, y):
            xs = np.flatnonzero(mask[y]); return xs.min() if xs.size else CANVAS_W / 2
        def right(mask, y):
            xs = np.flatnonzero(mask[y]); return xs.max() if xs.size else CANVAS_W / 2
        rs, ms = avg(ref_m, span), avg(mod_m, span)
        rc, mc = avg(ref_m, cov), avg(mod_m, cov)
        bands.append(dict(i=i, rs=rs, ms=ms, rc=rc, mc=mc,
                          dl=avg(mod_m, left) - avg(ref_m, left),     # + = model left edge further right (narrower)
                          dr=avg(mod_m, right) - avg(ref_m, right)))  # + = model right edge further right (wider)
    segs, cur = [], None
    for b in bands:
        rel = (b["ms"] - b["rs"]) / max(b["rs"], 1.0)
        sign = 0 if abs(rel) < REL_TOL else (1 if rel > 0 else -1)
        if sign and cur and cur["sign"] == sign and b["i"] == cur["b"][-1]["i"] + 1 and len(cur["b"]) < MAX_MERGE:
            cur["b"].append(b)
        else:
            if cur:
                segs.append(cur)
            cur = {"sign": sign, "b": [b]} if sign else None
    if cur:
        segs.append(cur)
    out = []
    for s in segs:
        bs = s["b"]
        area = sum(abs(b["ms"] - b["rs"]) for b in bs) / NORM_H          # in band-height units
        rs, ms = np.mean([b["rs"] for b in bs]), np.mean([b["ms"] for b in bs])
        rc, mc = np.mean([b["rc"] for b in bs]), np.mean([b["mc"] for b in bs])
        ftop, fbot = bs[0]["i"] / NBANDS, (bs[-1]["i"] + 1) / NBANDS
        dl, dr = np.mean([b["dl"] for b in bs]), np.mean([b["dr"] for b in bs])
        word = "wider" if s["sign"] > 0 else "narrower"
        rel = (ms - rs) / rs
        # which edge carries the error (wider: left edge moves left = dl<0, right edge right = dr>0)
        lw, rw = (-dl if s["sign"] > 0 else dl), (dr if s["sign"] > 0 else -dr)
        side = "both sides" if min(lw, rw) > 0.4 * max(lw, rw) else ("left edge" if lw > rw else "right edge")
        out.append(dict(
            from_top=round(ftop, 3), to_top=round(fbot, 3), sign=s["sign"], area=round(area, 4),
            rel_span_err=round(float(rel), 3), ref_span=round(float(rs / NORM_H), 3), model_span=round(float(ms / NORM_H), 3),
            ref_cover=round(float(rc / NORM_H), 3), model_cover=round(float(mc / NORM_H), 3),
            cover_rel_err=round(float((mc - rc) / max(rc, 1)), 3), side=side,
            z_hi_m=round((1 - ftop) * MODEL_HEIGHT_M, 0), z_lo_m=round((1 - fbot) * MODEL_HEIGHT_M, 0),
            text="model %d%% %s than reference %s, %s (span %.2f vs %.2f of height; filled width %+d%%)" % (
                round(abs(rel) * 100), word, rng_text(ftop, fbot, ortho), side,
                ms / NORM_H, rs / NORM_H, round((mc - rc) / max(rc, 1) * 100))))
    out.sort(key=lambda r: -r["area"])
    return out[:top]


def rng_text(ftop, fbot, ortho):
    if ortho:
        return "at z~%d-%d m" % (round((1 - fbot) * MODEL_HEIGHT_M), round((1 - ftop) * MODEL_HEIGHT_M))
    return "at %d-%d%% height" % (round((1 - fbot) * 100), round((1 - ftop) * 100))


# ----------------------------------------------------------------------------- sheet
def font(sz):
    for f in ("arial.ttf", "DejaVuSans.ttf"):
        try:
            return ImageFont.truetype(f, sz)
        except Exception:
            pass
    return ImageFont.load_default()


def overlay(ref_m, mod_m):
    o = np.full(ref_m.shape + (3,), 245, np.uint8)
    o[ref_m & ~mod_m] = (220, 30, 30)
    o[mod_m & ~ref_m] = (30, 60, 230)
    o[ref_m & mod_m] = (150, 60, 160)
    return o


def sheet(pid, ref_rgb, mod_rgb, ref_m, mod_m, sc, path):
    bgc = (236, 236, 238)
    panels = []
    for rgb, m in ((ref_rgb, ref_m), (mod_rgb, mod_m)):
        p = np.full((CANVAS_H, CANVAS_W, 3), bgc, np.uint8)
        # neutral backdrop, building pixels only (so the background colours do not matter)
        p[m] = rgb[m]
        panels.append(p)
    ov = overlay(ref_m, mod_m)
    for p in panels + [ov]:
        for i in range(NPROF + 1):                       # profile band edges as faint ticks
            y = MARGIN_TOP + int(round(i / NPROF * NORM_H))
            p[min(y, CANVAS_H - 1), :14] = (120, 120, 120)
            p[min(y, CANVAS_H - 1), -14:] = (120, 120, 120)
    top = 64
    S = Image.new("RGB", (CANVAS_W * 3, CANVAS_H + top), (255, 255, 255))
    for k, p in enumerate(panels + [ov]):
        S.paste(Image.fromarray(p), (k * CANVAS_W, top))
    d = ImageDraw.Draw(S)
    f1, f2 = font(22), font(16)
    d.text((10, 6), "%s   IoU(normalised) %.3f   IoU(raw frame) %.3f   [approximate guide - perspective refs vs orthographic model]" % (
        pid, sc["iou_normalised"], sc["iou_raw"]), fill=(0, 0, 0), font=f1)
    for k, t in enumerate(("REFERENCE (height-normalised)", "MODEL (height-normalised)",
                           "OVERLAY: red = ref only, blue = model only, purple = both")):
        d.text((k * CANVAS_W + 10, 38), t, fill=(60, 60, 60), font=f2)
    S.save(path)


# ----------------------------------------------------------------------------- main per pair
def run_pair(pid, tag, outdir):
    view, refpath, panel, primary, ortho = PAIRS[pid]
    mpath = os.path.join(ASM, "%s_%s.png" % (tag, view))
    if not os.path.exists(mpath) or not os.path.exists(refpath):
        return None
    rthr, mthr = THRESH_OVERRIDE.get(pid, (REF_THR, MODEL_THR))
    ref = load_frame(refpath, B02_BOX[panel] if panel else None)
    mod = load_frame(mpath)
    rm, mm = segment(ref, rthr, True), segment(mod, mthr)
    rrgb, rmn, rs = normalise(ref, rm)
    mrgb, mmn, ms = normalise(mod, mm)

    rb, mb = bbox(rm), bbox(mm)
    rh, mh = rb[3] - rb[1], mb[3] - mb[1]
    r_span, r_cov = profile(rmn, MARGIN_TOP, NORM_H)
    m_span, m_cov = profile(mmn, MARGIN_TOP, NORM_H)
    rr_span, rr_cov = profile(rm, rb[1], rh, denom=FRAME_H)
    mr_span, mr_cov = profile(mm, mb[1], mh, denom=FRAME_H)
    prof = []
    for i in range(NPROF):
        ft = (i + 0.5) / NPROF
        prof.append(dict(height_from_top=round(ft, 3), z_m=round((1 - ft) * MODEL_HEIGHT_M, 1),
                         ref_span=round(r_span[i], 4), model_span=round(m_span[i], 4),
                         span_diff=round(m_span[i] - r_span[i], 4),
                         ref_cover=round(r_cov[i], 4), model_cover=round(m_cov[i], 4),
                         cover_diff=round(m_cov[i] - r_cov[i], 4)))
    regs = regions(rmn, mmn, ortho)
    sc = dict(pair=pid, model_view=view, reference=os.path.relpath(refpath, ROOT).replace("\\", "/"),
              b02_panel=panel, primary=primary, orthographic_model=ortho, thresholds=dict(ref=rthr, model=mthr),
              iou_normalised=round(iou(rmn, mmn), 4), iou_raw=round(iou(rm, mm), 4),
              raw=dict(ref_bbox_px=list(rb), model_bbox_px=list(mb),
                       ref_height_frac=round(rh / FRAME_H, 3), model_height_frac=round(mh / FRAME_H, 3),
                       ref_width_frac_of_height=round((rb[2] - rb[0]) / rh, 3),
                       model_width_frac_of_height=round((mb[2] - mb[0]) / mh, 3),
                       ref_span_profile=[round(v, 4) for v in rr_span], model_span_profile=[round(v, 4) for v in mr_span],
                       note="raw profile = width / full frame height (1536), at 12 heights along each own bbox"),
              mean_abs_span_diff=round(float(np.mean([abs(p["span_diff"]) for p in prof])), 4),
              profile=prof, regions=regs)
    sheet(pid, rrgb, mrgb, rmn, mmn, sc, os.path.join(outdir, pid + ".png"))
    # debug: raw masks side by side so segmentation can be checked on the unnormalised images
    dbg = np.concatenate([np.where(rm[..., None], ref, 255 * 0 + 235).astype(np.uint8),
                          np.where(mm[..., None], mod, 235).astype(np.uint8)], axis=1)
    Image.fromarray(dbg).resize((dbg.shape[1] // 3, dbg.shape[0] // 3), Image.LANCZOS).save(os.path.join(outdir, "_seg_" + pid + ".png"))
    return sc


def write_summary(tag, scores, path):
    L = ["# Silhouette comparison: %s vs R06 references" % tag, "",
         "**Approximate guide, not pass/fail.** References are perspective AI concept renders; front/rear/left/right model renders are "
         "orthographic and the elevated ones use a different camera. Silhouettes are height-normalised and centred before scoring, which removes "
         "scale/framing differences but not perspective. Percentages are model vs reference silhouette width at the same fraction of height; "
         "z values assume the silhouette is 240 m tall (orthographic views only). Look at the sheets before acting.", "",
         "| pair | IoU normalised | IoU raw | mean abs span diff (frac of height) |", "|---|---|---|---|"]
    for s in scores:
        L.append("| %s%s | %.3f | %.3f | %.3f |" % (s["pair"], "" if s["primary"] else " (alt)", s["iou_normalised"], s["iou_raw"], s["mean_abs_span_diff"]))
    for s in scores:
        L += ["", "## %s (model `%s` vs `%s`%s)%s" % (s["pair"], s["model_view"], s["reference"],
              " panel " + s["b02_panel"] if s["b02_panel"] else "", "" if s["primary"] else " - alternate reference"),
              "IoU %.3f normalised, %.3f raw. Silhouette aspect (width/height): reference %.2f, model %.2f." % (
                  s["iou_normalised"], s["iou_raw"], s["raw"]["ref_width_frac_of_height"], s["raw"]["model_width_frac_of_height"])]
        if not s["regions"]:
            L.append("- No height band with more than %d%% span error." % round(REL_TOL * 100))
        for r in s["regions"][:5]:
            L.append("- " + r["text"])
    open(path, "w", encoding="utf-8").write("\n".join(L) + "\n")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("tag")
    ap.add_argument("--out", default=None)
    ap.add_argument("--only", default=None)
    args = ap.parse_args()
    outdir = args.out or os.path.join(ROOT, "out", "compare", args.tag)
    os.makedirs(outdir, exist_ok=True)
    ids = args.only.split(",") if args.only else list(PAIRS)
    scores = []
    for pid in ids:
        sc = run_pair(pid, args.tag, outdir)
        if sc is None:
            print("skip %s (missing model render or reference)" % pid)
            continue
        scores.append(sc)
        print("%-18s IoU norm %.3f  raw %.3f  mean|span diff| %.3f" % (pid, sc["iou_normalised"], sc["iou_raw"], sc["mean_abs_span_diff"]))
    json.dump({"tag": args.tag, "method_note": "approximate guide, not pass/fail; see compare.py docstring", "pairs": scores},
              open(os.path.join(outdir, "scores.json"), "w"), indent=1)
    write_summary(args.tag, scores, os.path.join(outdir, "SUMMARY.md"))
    print("wrote", outdir)


if __name__ == "__main__":
    main()
