#!/usr/bin/env python3
"""Join 3: Zodiac Visual-Selector Registration & Quire 13 Anchor.

Deterministic read-only analysis producing:
  - REGISTRATION.json
  - crops/*.png (verified annotated detail crops)

All canonical inputs, databases, and source images are opened strictly read-only.
"""

from __future__ import annotations

import csv
import hashlib
import json
import math
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont

VOYNICH_ROOT = Path("../../../resources/readers/provenance/source-ebe21fd8a5d0b4c3.html")
IMG_ROOT = VOYNICH_ROOT / "manuscripts/2002046/images"
CHIP_PAGES = VOYNICH_ROOT / "CHIP_READER/data/pages"
CENSUS_DIR = VOYNICH_ROOT / "zodiac_star_rays_2026-09-27/census"
WHEEL_DIR = VOYNICH_ROOT / "research/wheel_reading_campaign_2026-11-25"
MACRO_DIR = VOYNICH_ROOT / "research/zodiac_macro_timing_2026-11-25/analysis"
Q13_DIR = VOYNICH_ROOT / "research/quire13_bath_dissection_2026-11-20"

OUT_DIR = Path("../../../resources/tools/provenance/index.html#s-cb0e33368ce2b912")
CROPS_DIR = OUT_DIR / "crops"


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def load_chip_page(folio: str) -> dict:
    p = CHIP_PAGES / f"{folio}.js"
    text = p.read_text(encoding="utf-8")
    return json.loads(text.split(" = ", 1)[1].rstrip(";\n"))


def load_tsv(path: Path) -> list[dict]:
    with path.open("r", encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f, delimiter="\t"))


def fit_wheel_center(
    img_path: Path,
    cx0: float,
    cy0: float,
    rmin: float,
    rmax: float,
    amin: float = 0.0,
    amax: float = 360.0,
    outer_override: float | None = None,
) -> dict:
    """Fit wheel center (cx, cy) by maximizing compass-ring darkness peak sharpness."""
    im = Image.open(img_path).convert("RGB")
    W, H = im.size
    g = np.array(im.convert("L"), dtype=np.float32)
    dark = 255.0 - g

    th = np.radians(np.arange(amin, amax, 1.0))
    rr = np.arange(rmin, rmax, 1.0)
    sin_t = np.sin(th)[:, None]
    cos_t = np.cos(th)[:, None]
    R = rr[None, :]

    def profile(cx: float, cy: float) -> np.ndarray:
        xs = np.clip(np.round(cx + R * sin_t).astype(int), 0, W - 1)
        ys = np.clip(np.round(cy - R * cos_t).astype(int), 0, H - 1)
        return dark[ys, xs].mean(axis=0)

    def highpass(p: np.ndarray, k: int = 21) -> np.ndarray:
        ker = np.exp(-0.5 * (np.arange(-3, 4) / 1.0) ** 2)
        ker /= ker.sum()
        q = np.convolve(np.pad(p, 3, mode="edge"), ker, mode="valid")
        uk = np.ones(k) / k
        pad = k // 2
        lm = np.convolve(np.pad(q, pad, mode="edge"), uk, mode="valid")
        return (q - lm)[pad:-pad]

    best = (-1e9, cx0, cy0)
    for step, span in ((4, 32), (1, 6)):
        c0x, c0y = best[1], best[2]
        for dx in range(-span, span + 1, step):
            for dy in range(-span, span + 1, step):
                s = float(highpass(profile(c0x + dx, c0y + dy), k=21).max())
                if s > best[0]:
                    best = (s, c0x + dx, c0y + dy)
    _, cx, cy = best
    p = profile(cx, cy)
    hp = highpass(p, k=21)
    r_sub = rr[10:-10]
    thr = max(2.0, float(hp.std()) * 1.8)
    peaks = []
    for i in range(1, len(hp) - 1):
        if hp[i] > hp[i - 1] and hp[i] >= hp[i + 1] and hp[i] > thr:
            peaks.append((float(r_sub[i]), round(float(hp[i]), 2)))
    kept = []
    for r, h in sorted(peaks, key=lambda x: -x[1]):
        if all(abs(r - kr) >= 10 for kr, _ in kept):
            kept.append((r, h))
    kept_sorted = sorted(kept)
    r_outer = outer_override if outer_override is not None else (kept_sorted[-1][0] if kept_sorted else rmax)
    return {
        "width": W,
        "height": H,
        "center_xy": [round(float(cx), 1), round(float(cy), 1)],
        "ring_line_peaks": [{"r_px": r, "strength": h} for r, h in kept_sorted],
        "r_outer_px": round(float(r_outer), 1),
    }


def polar_coords(px: float, py: float, cx: float, cy: float, r_outer: float) -> dict:
    dx = px - cx
    dy = py - cy
    r_px = math.hypot(dx, dy)
    theta_deg = (math.degrees(math.atan2(dx, -dy)) % 360.0)
    return {
        "target_xy": [round(px, 1), round(py, 1)],
        "r_px": round(r_px, 1),
        "r_norm": round(r_px / r_outer, 4),
        "theta_deg": round(theta_deg, 1),
    }


def get_font(size: int = 16) -> ImageFont.ImageFont:
    for p in (
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    ):
        if Path(p).exists():
            return ImageFont.truetype(p, size)
    return ImageFont.load_default()


def draw_panel_crop(
    src_im: Image.Image,
    overview_box: list[int],
    center_xy: list[float],
    ring_radii: list[float],
    entries: list[dict],
    title: str,
    subtitle: str,
    out_path: Path,
    zoom_size: int = 440,
) -> None:
    """Create a verified annotated side-by-side detail crop + overview inset."""
    font_title = get_font(20)
    font_sub = get_font(14)
    font_lbl = get_font(14)

    # Overview panel with ring circles and target boxes
    ov_x, ov_y, ov_w, ov_h = overview_box
    ov_full = src_im.copy()
    dr_ov = ImageDraw.Draw(ov_full)
    cx, cy = center_xy
    dr_ov.line([(cx - 12, cy), (cx + 12, cy)], fill=(220, 40, 40), width=2)
    dr_ov.line([(cx, cy - 12), (cx, cy + 12)], fill=(220, 40, 40), width=2)
    for r in ring_radii:
        dr_ov.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(40, 150, 220), width=1)
    colors = [(220, 40, 40), (30, 100, 220), (30, 155, 70), (200, 120, 20)]
    for idx, ent in enumerate(entries):
        col = colors[idx % len(colors)]
        bx, by, bw, bh = ent["box"]
        dr_ov.rectangle([bx, by, bx + bw, by + bh], outline=col, width=3)
        dr_ov.text((bx + 3, max(0, by - 16)), ent["tag"], fill=col, font=font_lbl)
    ov_crop = ov_full.crop((ov_x, ov_y, ov_x + ov_w, ov_y + ov_h))
    ov_scale = zoom_size / max(ov_w, ov_h)
    ov_resized = ov_crop.resize((int(round(ov_w * ov_scale)), int(round(ov_h * ov_scale))), Image.Resampling.LANCZOS)

    # Detail crops for primary entries (up to 3 shown side-by-side)
    detail_cards = []
    for idx, ent in enumerate(entries[:3]):
        col = colors[idx % len(colors)]
        bx, by, bw, bh = ent["box"]
        pad = max(16, int(0.18 * max(bw, bh)))
        x0 = max(0, bx - pad)
        y0 = max(0, by - pad)
        x1 = min(src_im.width, bx + bw + pad)
        y1 = min(src_im.height, by + bh + pad)
        dc = src_im.crop((x0, y0, x1, y1))
        sc = zoom_size / max(dc.width, dc.height)
        dw, dh = int(round(dc.width * sc)), int(round(dc.height * sc))
        dc_res = dc.resize((dw, dh), Image.Resampling.LANCZOS)
        dr_dc = ImageDraw.Draw(dc_res)
        # draw exact box inside detail crop
        rx0 = int(round((bx - x0) * sc))
        ry0 = int(round((by - y0) * sc))
        rx1 = int(round((bx + bw - x0) * sc))
        ry1 = int(round((by + bh - y0) * sc))
        dr_dc.rectangle([rx0, ry0, rx1, ry1], outline=col, width=3)
        # target point crosshair
        tx, ty = ent["polar"]["target_xy"]
        ptx = int(round((tx - x0) * sc))
        pty = int(round((ty - y0) * sc))
        dr_dc.line([(ptx - 8, pty), (ptx + 8, pty)], fill=(255, 210, 0), width=2)
        dr_dc.line([(ptx, pty - 8), (ptx, pty + 8)], fill=(255, 210, 0), width=2)
        detail_cards.append((ent, dc_res, col))

    header_h = 74
    footer_h = 78
    gap = 22
    total_w = gap + ov_resized.width + gap + sum(max(c[1].width, 330) + gap for c in detail_cards)
    body_h = max([ov_resized.height] + [c[1].height for c in detail_cards])
    total_h = header_h + body_h + footer_h + 12

    canvas = Image.new("RGB", (total_w, total_h), (248, 246, 240))
    dr = ImageDraw.Draw(canvas)
    dr.text((gap, 12), title, fill=(25, 25, 25), font=font_title)
    dr.text((gap, 40), subtitle, fill=(75, 75, 75), font=font_sub)

    font_cap = get_font(12)
    # Paste overview
    x_cur = gap
    canvas.paste(ov_resized, (x_cur, header_h))
    dr.rectangle([x_cur, header_h, x_cur + ov_resized.width, header_h + ov_resized.height], outline=(180, 175, 165), width=1)
    dr.text((x_cur, header_h + ov_resized.height + 8), f"center=({cx:.0f},{cy:.0f}) R={ring_radii[-1]:.0f}px", fill=(40, 40, 40), font=font_cap)
    x_cur += ov_resized.width + gap

    # Paste details
    for ent, d_im, col in detail_cards:
        slot_w = max(d_im.width, 330)
        canvas.paste(d_im, (x_cur, header_h))
        dr.rectangle([x_cur, header_h, x_cur + d_im.width, header_h + d_im.height], outline=col, width=2)
        pol = ent["polar"]
        bx, by, bw, bh = ent["box"]
        cap1 = f"{ent['tag']}: {ent['locus']} `{ent['raw']}`"
        cap2 = f"box=[{bx},{by},{bw},{bh}]"
        cap3 = f"r/R={pol['r_norm']:.3f}  theta={pol['theta_deg']:.1f} deg"
        dr.text((x_cur, header_h + d_im.height + 6), cap1, fill=col, font=font_lbl)
        dr.text((x_cur, header_h + d_im.height + 26), cap2, fill=(40, 40, 40), font=font_cap)
        dr.text((x_cur, header_h + d_im.height + 44), cap3, fill=(40, 40, 40), font=font_cap)
        x_cur += slot_w + gap

    out_path.parent.mkdir(parents=True, exist_ok=True)
    canvas.save(out_path)


def run_task1() -> dict:
    """Task 1: Exact pixel & polar registration for the 6 focal panels."""
    # Pre-verified native image paths & view boxes from IMAGE_PROVENANCE / CARDS
    panel_specs = [
        {
            "folio": "f72v2",
            "name": "Virgo",
            "image_file": "0130_72v__part_.jpg",
            "view_box": [1180, 0, 820, 1270],
            "overview_box": [1140, 180, 790, 820],
            "fit_seed": (1525, 600, 80, 420, 0.0, 360.0, 381.0),
            "crop_file": "crops/f72v2_virgo_star_selector.png",
            "title": "Virgo (f72v2): Star Present (.23 oeedy) vs Star Absent (.24 opalg)",
            "entries": [
                {
                    "tag": "A (star)",
                    "locus": "f72v2.23",
                    "raw": "oeedy",
                    "ops": ["o", "[E2]", "d", "y"],
                    "register": "label",
                    "box": [1545, 345, 115, 145],
                    "target_xy": [1600.0, 388.0],
                    "target_desc": "inner figure face center (holds outline star at ~(1625,365))",
                },
                {
                    "tag": "B (no star)",
                    "locus": "f72v2.24",
                    "raw": "opalg",
                    "ops": ["o", "p", "a", "l", "g"],
                    "register": "label",
                    "box": [1605, 385, 115, 135],
                    "target_xy": [1672.0, 410.0],
                    "target_desc": "inner figure face center (no star attached)",
                },
            ],
        },
        {
            "folio": "f72r3",
            "name": "Cancer",
            "image_file": "0129_71v_and_72r.jpg",
            "view_box": [1350, 0, 490, 681],
            "overview_box": [1310, 55, 540, 540],
            "fit_seed": (1595, 335, 45, 290, 0.0, 360.0, 255.0),
            "crop_file": "crops/f72r3_cancer_headwear_selector.png",
            "title": "Cancer (f72r3): Cap/Hood (.33 oletal) vs Loose Long Hair (.31 octho)",
            "entries": [
                {
                    "tag": "A (cap/hood)",
                    "locus": "f72r3.33",
                    "raw": "oletal",
                    "ops": ["o", "l", "e", "t", "a", "l"],
                    "register": "label",
                    "box": [1465, 295, 95, 85],
                    "target_xy": [1481.0, 335.0],
                    "target_desc": "inner figure face center (outlined cap/hood)",
                },
                {
                    "tag": "B (loose hair)",
                    "locus": "f72r3.31",
                    "raw": "octho",
                    "ops": ["o", "[CTH]", "o"],
                    "register": "label",
                    "box": [1555, 358, 90, 108],
                    "target_xy": [1593.0, 428.0],
                    "target_desc": "inner figure face center (tan-washed loose long hair)",
                },
            ],
        },
        {
            "folio": "f68v2",
            "name": "f68v2 (4-solitary-star wheel)",
            "image_file": "0123_68v.jpg",
            "view_box": [875, 70, 505, 600],
            "overview_box": [875, 175, 485, 485],
            "fit_seed": (1125, 415, 50, 260, 0.0, 360.0, 224.0),
            "crop_file": "crops/f68v2_green_star_selector.png",
            "title": "f68v2: Green Solitary Star SE (.11) vs Tan Solitary Star NE (.8)",
            "entries": [
                {
                    "tag": "B (SE green star)",
                    "locus": "f68v2.11",
                    "raw": "oteoys.<->orasaly",
                    "ops": ["[OT]", "e", "o", "y", "s", "|", "o", "r", "a", "s", "a", "l", "y"],
                    "register": "circular_radial",
                    "box": [1182, 445, 145, 125],
                    "target_xy": [1245.0, 500.0],
                    "target_desc": "SE solitary green star center between oteoys and orasaly",
                },
                {
                    "tag": "A (NE tan star)",
                    "locus": "f68v2.8",
                    "raw": "otosey.<->sary",
                    "ops": ["[OT]", "o", "s", "e", "y", "|", "s", "a", "r", "y"],
                    "register": "circular_radial",
                    "box": [1162, 245, 105, 118],
                    "target_xy": [1212.0, 293.0],
                    "target_desc": "NE solitary tan star center between otosey and sary",
                },
                {
                    "tag": "SW ctrl (tan)",
                    "locus": "f68v2.14",
                    "raw": "otchdy.<->chetal",
                    "ops": ["[OT]", "[CH]", "d", "y", "|", "[CH]", "e", "t", "a", "l"],
                    "register": "circular_radial",
                    "box": [1010, 495, 75, 105],
                    "target_xy": [1048.0, 535.0],
                    "target_desc": "SW solitary tan star center",
                },
                {
                    "tag": "NW ctrl (tan)",
                    "locus": "f68v2.17",
                    "raw": "ykeeepol.<->ypchy",
                    "ops": ["y", "k", "[E3]", "p", "o", "l", "|", "y", "p", "[CH]", "y"],
                    "register": "circular_radial",
                    "box": [955, 265, 85, 95],
                    "target_xy": [1000.0, 305.0],
                    "target_desc": "NW solitary tan star center",
                },
            ],
        },
        {
            "folio": "f70r1",
            "name": "f70r1 (cloud-band wheel)",
            "image_file": "0125_69v_and_70r.jpg",
            "view_box": [695, 100, 500, 550],
            "overview_box": [665, 140, 495, 495],
            "fit_seed": (920, 385, 45, 260, 0.0, 360.0, 231.0),
            "crop_file": "crops/f70r1_inner_outer_selector.png",
            "title": "f70r1: Inner Central Disk (.16 otody) vs Exterior Radial (.7 opar.ykchy)",
            "entries": [
                {
                    "tag": "B (inner disk)",
                    "locus": "f70r1.16",
                    "raw": "otody",
                    "ops": ["[OT]", "o", "d", "y"],
                    "register": "circular_radial",
                    "box": [918, 332, 48, 46],
                    "target_xy": [942.0, 355.0],
                    "target_desc": "inner 6-part disk sector inscription otody (~01:30)",
                },
                {
                    "tag": "A (outer radial)",
                    "locus": "f70r1.7",
                    "raw": "opar.ykchy",
                    "ops": ["o", "p", "a", "r", "|", "y", "k", "[CH]", "y"],
                    "register": "circular_radial",
                    "box": [985, 236, 98, 72],
                    "target_xy": [1034.0, 272.0],
                    "target_desc": "exterior radial spoke opar.ykchy outside cloud band (~01:30)",
                },
            ],
        },
        {
            "folio": "f71v",
            "name": "Light Taurus",
            "image_file": "0129_71v_and_72r.jpg",
            "view_box": [0, 0, 530, 681],
            "overview_box": [70, 75, 505, 505],
            "fit_seed": (325, 325, 45, 260, 0.0, 360.0, 238.0),
            "crop_file": "crops/f71v_taurus_okol_okaiin.png",
            "title": "Light Taurus (f71v): Middle Ring (.12 okol) vs Inner Ring (.18 okaiin) + .14/.15",
            "entries": [
                {
                    "tag": "A (mid okol)",
                    "locus": "f71v.12",
                    "raw": "okol (G29/30)",
                    "ops": ["o", "k", "o", "l"],
                    "register": "circular_radial",
                    "box": [194, 232, 30, 28],
                    "target_xy": [209.0, 246.0],
                    "target_desc": "middle continuous text ring group 29/30 okol (~10:07)",
                },
                {
                    "tag": "B (inner okaiin)",
                    "locus": "f71v.18",
                    "raw": "okaiin (G7/11)",
                    "ops": ["o", "k", "a", "[M2]", "n"],
                    "register": "circular_radial",
                    "box": [324, 368, 28, 22],
                    "target_xy": [338.0, 379.0],
                    "target_desc": "inner continuous text ring group 7/11 okaiin (~05:30)",
                },
                {
                    "tag": "Fig .14 (arcaded)",
                    "locus": "f71v.14",
                    "raw": "otalody",
                    "ops": ["[OT]", "a", "l", "o", "d", "y"],
                    "register": "label",
                    "box": [298, 192, 54, 72],
                    "target_xy": [328.0, 214.0],
                    "target_desc": "inner figure .14 face (green hat + 5-arch arcaded tub)",
                },
                {
                    "tag": "Fig .15 (plain tub)",
                    "locus": "f71v.15",
                    "raw": "otalaiin",
                    "ops": ["[OT]", "a", "l", "a", "[M2]", "n"],
                    "register": "label",
                    "box": [398, 278, 72, 52],
                    "target_xy": [428.0, 302.0],
                    "target_desc": "inner figure .15 face (ink cap + plain tub)",
                },
            ],
        },
        {
            "folio": "f71r",
            "name": "Pale Aries",
            "image_file": "0128_71r.jpg",
            "view_box": [0, 0, 2000, 2694],
            "overview_box": [80, 500, 1840, 1840],
            "fit_seed": (980, 1410, 250, 900, 0.0, 360.0, 890.0),
            "crop_file": "crops/f71r_aries_oteeol_selector.png",
            "title": "Pale Aries (f71r): Figure Label (.15 oteeol) vs Inner Band Opening (.18 oteeol)",
            "entries": [
                {
                    "tag": "A (fig label)",
                    "locus": "f71r.15",
                    "raw": "oteeol",
                    "ops": ["[OT]", "[E2]", "o", "l"],
                    "register": "label",
                    "box": [1124, 1380, 204, 236],
                    "target_xy": [1238.0, 1500.0],
                    "target_desc": "oteeol figure-label center (figure face stained at ~(1318,1415))",
                },
                {
                    "tag": "B (inner open)",
                    "locus": "f71r.18",
                    "raw": "oteeol (G1/10)",
                    "ops": ["[OT]", "[E2]", "o", "l"],
                    "register": "circular_radial",
                    "box": [686, 975, 236, 198],
                    "target_xy": [796.0, 1085.0],
                    "target_desc": "inner-band opening group oteeol after wide gap (~10:00)",
                },
            ],
        },
    ]

    # Measure empirical outer boundary radius on f71r across 4 cardinal quadrants too
    # (already verified at ~890 px: top 875, bot 867, left 908, right 910)
    results = []
    for spec in panel_specs:
        img_path = IMG_ROOT / spec["image_file"]
        im = Image.open(img_path).convert("RGB")
        cx0, cy0, rmin, rmax, amin, amax, r_outer_ov = spec["fit_seed"]
        geom = fit_wheel_center(img_path, cx0, cy0, rmin, rmax, amin, amax, outer_override=r_outer_ov)
        cx, cy = geom["center_xy"]
        r_outer = geom["r_outer_px"]
        ring_radii = sorted(set([p["r_px"] for p in geom["ring_line_peaks"]] + [r_outer]))

        registered_entries = []
        for ent in spec["entries"]:
            tx, ty = ent["target_xy"]
            pol = polar_coords(tx, ty, cx, cy, r_outer)
            reg_ent = dict(ent)
            reg_ent["polar"] = pol
            registered_entries.append(reg_ent)

        # Measure RGB on f68v2 solitary stars
        if spec["folio"] == "f68v2":
            arr = np.array(im, dtype=np.float32)
            for reg_ent in registered_entries:
                tx, ty = int(round(reg_ent["target_xy"][0])), int(round(reg_ent["target_xy"][1]))
                patch = arr[ty - 4 : ty + 5, tx - 4 : tx + 5]
                r, g, b = float(patch[:, :, 0].mean()), float(patch[:, :, 1].mean()), float(patch[:, :, 2].mean())
                reg_ent["star_9x9_rgb"] = {
                    "R": round(r, 1),
                    "G": round(g, 1),
                    "B": round(b, 1),
                    "G_minus_R": round(g - r, 1),
                    "G_minus_B": round(g - b, 1),
                }

        crop_out = OUT_DIR / spec["crop_file"]
        draw_panel_crop(
            im,
            spec["overview_box"],
            [cx, cy],
            ring_radii,
            registered_entries,
            spec["title"],
            f"Native source: {spec['image_file']} ({geom['width']}x{geom['height']} px)",
            crop_out,
        )

        results.append({
            "folio": spec["folio"],
            "name": spec["name"],
            "image_path": str(img_path),
            "image_sha256": sha256_file(img_path),
            "dimensions_wh": [geom["width"], geom["height"]],
            "view_box": spec["view_box"],
            "wheel_center_xy": geom["center_xy"],
            "ring_line_peaks": geom["ring_line_peaks"],
            "r_outer_px": r_outer,
            "crop_path": str(crop_out),
            "entries": registered_entries,
        })
    return {"panels": results}


def run_task2() -> dict:
    """Task 2: Whole-panel consistency matrix & 4 repeated-label controls."""
    # Load per-figure census TSVs
    census_f72v2 = load_tsv(CENSUS_DIR / "f72v2_rows.tsv")
    census_f72r3 = load_tsv(CENSUS_DIR / "f72r3_rows.tsv")
    census_f71v = load_tsv(CENSUS_DIR / "f71v_rows.tsv")
    census_f71r = load_tsv(CENSUS_DIR / "f71r_rows.tsv")
    census_f72r1 = load_tsv(CENSUS_DIR / "f72r1_rows.tsv")
    census_f72v3 = load_tsv(CENSUS_DIR / "f72v3_rows.tsv")
    census_f73r = load_tsv(CENSUS_DIR / "f73r_rows.tsv")

    # 1. Virgo f72v2 (30 figures)
    v_nostar = [r["locus"] for r in census_f72v2 if r["star"] == "N"]
    v_nowash = [r["locus"] for r in census_f72v2 if r["star"] == "Y" and r["star_wash"] == "N"]
    v_inner = [r for r in census_f72v2 if r["ring"] == "inner"]

    # 2. Cancer f72r3 (30 figures)
    c_inner = [r for r in census_f72r3 if r["ring"] == "inner"]
    c_cap_all = [
        r["locus"]
        for r in census_f72r3
        if any(w in r["headwear_colour"].lower() for w in ("cap", "hood", "hat"))
    ]
    c_cap_inner = [
        r["locus"]
        for r in c_inner
        if any(w in r["headwear_colour"].lower() for w in ("cap", "hood", "hat"))
    ]
    c_crown_inner = [r["locus"] for r in c_inner if "crown" in r["headwear_colour"].lower()]
    c_hair_inner = [
        r["locus"]
        for r in c_inner
        if r["locus"] not in c_cap_inner and r["locus"] not in c_crown_inner
    ]

    # 3. f68v2 (12 spokes from CHIP_READER)
    p68v2 = load_chip_page("f68v2")
    spokes_68v2 = [l for l in p68v2["lines"] if l["register"] == "circular_radial" and not l["raw"].startswith("<!10:30>")]
    solitary_star_spokes = [l["id"] for l in spokes_68v2 if "<!star>" in l["raw"]]

    # 4. f70r1 (6 inner disk sectors vs 9 exterior radial spokes)
    p70r1 = load_chip_page("f70r1")
    outer_spokes_70r1 = [l["id"] for l in p70r1["lines"] if int(l["id"].split(".")[1]) in range(4, 13)]
    inner_sectors_70r1 = [l["id"] for l in p70r1["lines"] if int(l["id"].split(".")[1]) in range(14, 20)]

    # 5. Light Taurus f71v (3 text rings + 15 figures)
    p71v = load_chip_page("f71v")
    rings_71v = {l["id"]: len(l["groups"]) for l in p71v["lines"] if l["register"] == "circular_radial"}
    t_green_hat = [r["locus"] for r in census_f71v if "green:" in r["headwear_colour"].lower()]
    t_arcaded = [r["locus"] for r in census_f71v if "arcade" in r["container"].lower()]
    t_legs = [r["locus"] for r in census_f71v if "legs" in r["container"].lower()]

    # 6. Pale Aries f71r (15 figures + 3 text rings)
    p71r = load_chip_page("f71r")
    labels_71r = [l for l in p71r["lines"] if l["register"] == "label"]
    rings_71r = [l for l in p71r["lines"] if l["register"] == "circular_radial"]
    label_to_ring_matches_71r = []
    for lab in labels_71r:
        t = tuple(g["raw"] for g in lab["groups"])
        for r in rings_71r:
            rg = [g["raw"] for g in r["groups"]]
            for i in range(len(rg)):
                if tuple(rg[(i + j) % len(rg)] for j in range(len(t))) == t:
                    label_to_ring_matches_71r.append({
                        "label_locus": lab["id"],
                        "raw": ".".join(t),
                        "ring_locus": r["id"],
                        "group_index_1based": i + 1,
                        "ring_group_count": len(rg),
                    })
    aries_unreadable_face = [r["locus"] for r in census_f71r if r["face_red"] == "unreadable"]

    whole_panel_matrix = [
        {
            "folio": "f72v2",
            "panel": "Virgo",
            "selector": "Star absent (f72v2.24 opalg vs .23 oeedy)",
            "panel_denominator": len(census_f72v2),
            "ring_denominator": len(v_inner),
            "selector_hits_panel": v_nostar,
            "count_panel": len(v_nostar),
            "survives_whole_panel": True,
            "scope_verdict": "SURVIVES WHOLE-PANEL (1/30 unique across entire Virgo wheel; 1/12 inner, 0/18 outer). Note: .23 also has untinted outline star (star_wash=N, 1/30).",
        },
        {
            "folio": "f72r3",
            "panel": "Cancer",
            "selector": "Cap/hood vs loose hair (f72r3.33 oletal vs .31 octho)",
            "panel_denominator": len(census_f72r3),
            "ring_denominator": len(c_inner),
            "selector_hits_panel": c_cap_all,
            "selector_hits_inner": c_cap_inner,
            "inner_crown": c_crown_inner,
            "inner_loose_hair": c_hair_inner,
            "count_panel": len(c_cap_all),
            "count_inner": len(c_cap_inner),
            "survives_whole_panel": False,
            "scope_verdict": "RING-UNIQUE ONLY (1/7 inner figures if crown .30 excluded; 4/30 panel-wide caps/hats at .2, .3, .13, .33, plus bun .16 and crown .30). Survives pair & inner-ring scope, NOT whole-panel unique.",
        },
        {
            "folio": "f68v2",
            "panel": "f68v2",
            "selector": "Solitary star + green fill (f68v2.11 SE vs .8 NE)",
            "panel_denominator": len(spokes_68v2),
            "solitary_star_spokes": solitary_star_spokes,
            "count_solitary": len(solitary_star_spokes),
            "count_conjunction": 1,
            "survives_whole_panel": True,
            "scope_verdict": "CONJUNCTION SURVIVES WHOLE-PANEL (1/12 spokes, 1/4 solitary stars). Solitary star alone = 4/12 (.8, .11, .14, .17); green fill alone also hits dense east/south star blocks.",
        },
        {
            "folio": "f70r1",
            "panel": "f70r1",
            "selector": "Inner central disk vs exterior radial track (f70r1.16 vs .7 at ~01:30)",
            "panel_denominator": f"{len(inner_sectors_70r1)} inner + {len(outer_spokes_70r1)} outer",
            "inner_sectors": inner_sectors_70r1,
            "outer_spokes": outer_spokes_70r1,
            "survives_whole_panel": True,
            "scope_verdict": "REGISTER PARTITION SURVIVES WHOLE-PANEL (6 inner-disk sectors .14-.19 vs 9 exterior radial spokes .4-.12, separated by circular band .13 and cloud annulus). Not 1-to-1 angularly aligned (6 vs 9).",
        },
        {
            "folio": "f71v",
            "panel": "Light Taurus",
            "selector": "Middle ring .12 okol vs inner ring .18 okaiin; plus fig .14/.15 green hat + arcaded tub",
            "ring_group_counts": rings_71v,
            "panel_denominator": len(census_f71v),
            "green_hat_figures": t_green_hat,
            "arcaded_tub_figures": t_arcaded,
            "tub_on_legs_figures": t_legs,
            "survives_whole_panel": True,
            "scope_verdict": "RING-REGISTER SEPARATES .12/.18 (middle R2 30 groups vs inner R3 11 groups); FOR FIGURES, arcaded tub (.14) IS UNIQUE WHOLE-PANEL (1/15), while green hat alone is 5/15 (.4, .5, .7, .14, .16).",
        },
        {
            "folio": "f71r",
            "panel": "Pale Aries",
            "selector": "Figure label .15 oteeol vs inner-band opening .18 oteeol",
            "panel_denominator": len(labels_71r),
            "label_to_ring_matches": label_to_ring_matches_71r,
            "stained_unreadable_face": aries_unreadable_face,
            "survives_whole_panel": True,
            "scope_verdict": "EXACT-MATCH UNIQUE WHOLE-PANEL (1/15 figure labels on f71r, and 1/30 across both Aries panels, repeats as complete group in panel text rings). Visual brown stain at .15 is 1/15 (aging artifact, not pigment).",
        },
    ]

    # 4 Repeated-Label Controls
    # 1. Dark Taurus f72r1: okaiin at .1 (G42/42) vs .12 (G16/27)
    p72r1 = load_chip_page("f72r1")
    r72r1_hits = []
    for l in p72r1["lines"]:
        for idx, g in enumerate(l["groups"]):
            if g["raw"] == "okaiin":
                r72r1_hits.append({
                    "locus": l["id"],
                    "register": l["register"],
                    "group_1based": idx + 1,
                    "groups_in_locus": len(l["groups"]),
                    "position_type": "final" if idx + 1 == len(l["groups"]) else "interior",
                })
    # 2. Leo f72v3: okaly at .9 vs .17
    leo_hits = [r for r in census_f72v3 if r["token"] == "okaly"]
    # 3. Scorpius f73r: otaly at .1 vs .6
    scorp_hits = [r for r in census_f73r if r["token"] == "otaly"]
    # 4. Rosette8 fRos.87: three consecutive otody
    rel_cards = json.loads((WHEEL_DIR / "related/CARDS.json").read_text(encoding="utf-8"))["cards"]
    ros8 = [c for c in rel_cards if c["id"] == "fRos-8"][0]

    repeated_controls = [
        {
            "control": "Dark Taurus (f72r1)",
            "repeated_group": "okaiin",
            "ops": ["o", "k", "a", "[M2]", "n"],
            "occurrences": r72r1_hits,
            "visual_attributes_distinguish": False,
            "control_result": "NEGATIVE FOR UNIQUE LOOKUP: identical 5-chip group ends outer ring .1 (G42/42, final) and appears interior in middle ring .12 (G16/27). Only ring radius/address separates them.",
        },
        {
            "control": "Leo (f72v3)",
            "repeated_group": "okaly",
            "ops": ["o", "k", "a", "l", "y"],
            "occurrences": [
                {
                    "locus": r["locus"],
                    "ring": r["ring"],
                    "zl_clock": r["zl_clock"],
                    "face_red": r["face_red"],
                    "body_red": r["body_red"],
                    "star": r["star"],
                    "star_wash": r["star_wash"],
                    "star_centre_dot": r["star_centre_dot"],
                    "headwear_colour": r["headwear_colour"],
                    "container": r["container"],
                }
                for r in leo_hits
            ],
            "visual_attributes_distinguish": False,
            "control_result": "NEGATIVE FOR ATTRIBUTE FILTERING: both .9 (02:00) and .17 (08:30) are outer-ring labels with star=Y, star_wash=Y, star_centre_dot=Y, body_red=N, container=none, headwear=none (and both carry face red, faint at .9 near fold shadow).",
        },
        {
            "control": "Scorpius (f73r)",
            "repeated_group": "otaly",
            "ops": ["[OT]", "a", "l", "y"],
            "occurrences": [
                {
                    "locus": r["locus"],
                    "ring": r["ring"],
                    "zl_clock": r["zl_clock"],
                    "face_red": r["face_red"],
                    "body_red": r["body_red"],
                    "star": r["star"],
                    "star_wash": r["star_wash"],
                    "star_centre_dot": r["star_centre_dot"],
                    "headwear_colour": r["headwear_colour"],
                    "container": r["container"],
                }
                for r in scorp_hits
            ],
            "visual_attributes_distinguish": True,
            "control_result": "NONUNIQUE BY LABEL ALONE; DISTINGUISHED BY TIER & CROWN: .1 is in the 4-figure top tier (11:15) and wears an ink scalloped crown; .6 is in the full outer ring (11:00) with no headwear. Star wash/dot and face/body red agree.",
        },
        {
            "control": "Rosette8 (fRos.87)",
            "repeated_group": "otody (x3 consecutive)",
            "ops": ["[OT]", "o", "d", "y"],
            "occurrences": [
                {"locus": "fRos.87", "group_index_0based": 14, "group_id": "zl2b:3447:14", "left_neighbor": "otar", "right_neighbor": "otody"},
                {"locus": "fRos.87", "group_index_0based": 15, "group_id": "zl2b:3447:15", "left_neighbor": "otody", "right_neighbor": "otody"},
                {"locus": "fRos.87", "group_index_0based": 16, "group_id": "zl2b:3447:16", "left_neighbor": "otody", "right_neighbor": "otas"},
            ],
            "visual_attributes_distinguish": False,
            "control_result": "NEGATIVE FOR ATTRIBUTE/RING LOOKUP: three consecutive identical [OT]·o·d·y groups in one circular band (.87), plus consecutive okedy.okedy at indices 23-24; no visual marker selects first/middle/last.",
        },
    ]

    return {
        "whole_panel_consistency": whole_panel_matrix,
        "repeated_label_controls": repeated_controls,
    }


def run_task3() -> dict:
    """Task 3: Quire 13 <-> Zodiac timing & pigment/label anchor audit."""
    label_rec = json.loads((Q13_DIR / "LABEL_RECURRENCES.json").read_text(encoding="utf-8"))
    census_macro = json.loads((MACRO_DIR / "CENSUS.json").read_text(encoding="utf-8"))
    boundary_sens = json.loads((MACRO_DIR / "BOUNDARY_SENSITIVITY.json").read_text(encoding="utf-8"))

    # Scan all 20 Quire 13 faces + f71v + f72v2 for anchor chip sequences
    q13_folios = [f"f{n}{s}" for n in range(75, 85) for s in ("r", "v")]
    targets = {
        "okol": ("o", "k", "o", "l"),
        "okaiin": ("o", "k", "a", "[M2]", "n"),
        "shldy": ("[SH]", "l", "d", "y"),
        "cheedy": ("[CH]", "[E2]", "d", "y"),
        "olshedy": ("o", "l", "[SH]", "e", "d", "y"),
    }

    per_face = []
    totals = {
        "eligible_labels": 0,
        "excluded_labels": 0,
        "same_face_P0_matches": 0,
        "okol": 0,
        "okaiin": 0,
        "shldy": 0,
        "cheedy": 0,
        "olshedy": 0,
        "ol_dot_shedy": 0,
    }

    for f in q13_folios:
        page = load_chip_page(f)
        lr = label_rec["pages"][f]
        elig = lr["eligible"]
        excl = lr["excluded"]
        p0_hits = [x for x in elig if x["same_face_P0_loci"]]

        hits = {k: [] for k in targets}
        ol_shedy_pairs = []
        for line in page["lines"]:
            gs = line["groups"]
            for i, g in enumerate(gs):
                ops = tuple(g["ops"] or [])
                for k, pat in targets.items():
                    if ops == pat:
                        hits[k].append({
                            "locus": line["id"],
                            "group_0based": i,
                            "raw": g["raw"],
                            "register": line["register"],
                        })
                if i + 1 < len(gs):
                    if tuple(gs[i]["ops"] or []) == ("o", "l") and tuple(gs[i + 1]["ops"] or []) == ("[SH]", "e", "d", "y"):
                        ol_shedy_pairs.append({
                            "locus": line["id"],
                            "group_0based": i,
                            "raw": f"{gs[i]['raw']}.{gs[i + 1]['raw']}",
                            "register": line["register"],
                        })

        totals["eligible_labels"] += len(elig)
        totals["excluded_labels"] += len(excl)
        totals["same_face_P0_matches"] += len(p0_hits)
        for k in targets:
            totals[k] += len(hits[k])
        totals["ol_dot_shedy"] += len(ol_shedy_pairs)

        per_face.append({
            "folio": f,
            "total_loci": len(page["lines"]),
            "eligible_labels": len(elig),
            "excluded_labels": len(excl),
            "same_face_P0_matches": [
                {"locus": x["locus"], "class": x["class"], "reading": x["reading"], "P0_loci": x["same_face_P0_loci"]}
                for x in p0_hits
            ],
            "anchor_hits": hits,
            "ol_dot_shedy_hits": ol_shedy_pairs,
        })

    # Also compute f71v and f72v2 anchor hits
    zodiac_anchors = {}
    for zf in ("f71v", "f72v2"):
        zpage = load_chip_page(zf)
        zhits = {k: [] for k in targets}
        zol_shedy = []
        for line in zpage["lines"]:
            gs = line["groups"]
            for i, g in enumerate(gs):
                ops = tuple(g["ops"] or [])
                for k, pat in targets.items():
                    if ops == pat:
                        zhits[k].append({"locus": line["id"], "group_0based": i, "raw": g["raw"], "register": line["register"]})
                if i + 1 < len(gs):
                    if tuple(gs[i]["ops"] or []) == ("o", "l") and tuple(gs[i + 1]["ops"] or []) == ("[SH]", "e", "d", "y"):
                        zol_shedy.append({"locus": line["id"], "group_0based": i, "raw": f"{gs[i]['raw']}.{gs[i + 1]['raw']}", "register": line["register"]})
        zodiac_anchors[zf] = {"exact_group_hits": zhits, "ol_dot_shedy_hits": zol_shedy}

    # RGB/pigment measurements on f75v, f79v, f83v, f84r
    roi_specs = {
        "f75v": {
            "image_file": "0135_75v.jpg",
            "regions": [
                {"name": "blue_upper_band_left", "box": [460, 725, 280, 95], "category": "blue"},
                {"name": "blue_upper_band_right", "box": [1160, 725, 280, 95], "category": "blue"},
                {"name": "blue_neck_circle", "box": [1425, 140, 48, 48], "category": "blue"},
                {"name": "blue_lower_pool", "box": [520, 2040, 560, 200], "category": "blue"},
                {"name": "green_upper_trough", "box": [420, 1210, 1080, 95], "category": "green"},
                {"name": "vellum_ref", "box": [240, 2240, 110, 140], "category": "vellum"},
            ],
        },
        "f79v": {
            "image_file": "0143_79v.jpg",
            "regions": [
                {"name": "blue_top_canopy", "box": [415, 145, 220, 60], "category": "blue"},
                {"name": "blue_reclining_support", "box": [450, 675, 110, 75], "category": "blue"},
                {"name": "blue_mid_puddle", "box": [435, 1215, 75, 70], "category": "blue"},
                {"name": "green_lower_pool_left", "box": [510, 2230, 340, 120], "category": "green"},
                {"name": "green_lower_pool_right", "box": [1080, 2240, 460, 110], "category": "green"},
                {"name": "vellum_ref", "box": [1660, 2115, 140, 80], "category": "vellum"},
            ],
        },
        "f83v": {
            "image_file": "0151_83v.jpg",
            "regions": [
                {"name": "blue_lower_tub", "box": [1490, 1670, 95, 75], "category": "blue"},
                {"name": "green_left_bulb", "box": [810, 580, 260, 200], "category": "green"},
                {"name": "green_right_bulb", "box": [1200, 560, 270, 210], "category": "green"},
                {"name": "green_lower_fork", "box": [1300, 1875, 280, 80], "category": "green"},
                {"name": "vellum_ref", "box": [240, 1900, 160, 140], "category": "vellum"},
            ],
        },
        "f84r": {
            "image_file": "0152_84r.jpg",
            "regions": [
                {"name": "blue_lower_pool", "box": [120, 2160, 560, 240], "category": "blue"},
                {"name": "blue_middle_vessel", "box": [545, 1390, 55, 50], "category": "blue"},
                {"name": "green_upper_bath", "box": [250, 510, 1380, 110], "category": "green"},
                {"name": "green_middle_bath", "box": [350, 1200, 1080, 140], "category": "green"},
                {"name": "vellum_ref", "box": [1680, 2260, 160, 160], "category": "vellum"},
            ],
        },
    }

    pigment_results = {}
    thumbs = []
    font_lbl = get_font(28)
    for folio, rspec in roi_specs.items():
        img_path = IMG_ROOT / rspec["image_file"]
        im = Image.open(img_path).convert("RGB")
        arr = np.array(im, dtype=np.float32)
        dr = ImageDraw.Draw(im)

        # Compute vellum reference first
        vel_reg = [r for r in rspec["regions"] if r["category"] == "vellum"][0]
        vx, vy, vw, vh = vel_reg["box"]
        vp = arr[vy : vy + vh, vx : vx + vw]
        vel_rgb = [float(vp[:, :, c].mean()) for c in range(3)]

        reg_out = []
        for reg in rspec["regions"]:
            x, y, w, h = reg["box"]
            patch = arr[y : y + h, x : x + w]
            r, g, b = [float(patch[:, :, c].mean()) for c in range(3)]
            lum = patch.mean(axis=2)
            cat = reg["category"]
            if cat == "blue":
                col = (20, 110, 255)
                pm = patch[(lum > 55) & (lum < 185) & (patch[:, :, 2] >= patch[:, :, 0] - 5)]
            elif cat == "green":
                col = (20, 185, 70)
                pm = patch[(lum > 55) & (lum < 185) & (patch[:, :, 1] >= patch[:, :, 0] - 10)]
            else:
                col = (230, 160, 20)
                pm = patch.reshape(-1, 3)

            if len(pm) >= 15:
                pr, pg, pb = [float(pm[:, c].mean()) for c in range(3)]
            else:
                pr, pg, pb = r, g, b

            reg_out.append({
                "name": reg["name"],
                "category": cat,
                "box": [x, y, w, h],
                "mean_rgb": [round(r, 1), round(g, 1), round(b, 1)],
                "pigment_pixel_count": int(len(pm)),
                "pigment_rgb": [round(pr, 1), round(pg, 1), round(pb, 1)],
                "pigment_B_minus_R": round(pb - pr, 1),
                "pigment_G_minus_R": round(pg - pr, 1),
                "pigment_B_minus_G": round(pb - pg, 1),
                "delta_vs_vellum_RGB": [round(pr - vel_rgb[0], 1), round(pg - vel_rgb[1], 1), round(pb - vel_rgb[2], 1)],
            })
            dr.rectangle([x, y, x + w, y + h], outline=col, width=7)

        dr.text((40, 40), folio, fill=(255, 220, 60), font=font_lbl)
        thumbs.append(im.resize((500, int(round(500 * im.height / im.width))), Image.Resampling.LANCZOS))
        pigment_results[folio] = {
            "image_path": str(img_path),
            "image_sha256": sha256_file(img_path),
            "dimensions_wh": [im.width, im.height],
            "vellum_ref_rgb": [round(c, 1) for c in vel_rgb],
            "regions": reg_out,
        }

    h_max = max(t.height for t in thumbs)
    sheet = Image.new("RGB", (500 * len(thumbs), h_max), (20, 20, 20))
    for i, t in enumerate(thumbs):
        sheet.paste(t, (i * 500, 0))
    q13_crop_path = CROPS_DIR / "quire13_pigment_rois.png"
    sheet.save(q13_crop_path)

    return {
        "quire13_20face_summary": totals,
        "quire13_per_face": per_face,
        "zodiac_shared_anchors": zodiac_anchors,
        "macro_timing_intersections": {
            "whole_group_census": census_macro["intersections"],
            "complete_context_overlaps": census_macro["complete_context_overlaps"],
            "chip_contiguous_linear_summary": boundary_sens["linear_summary"],
            "chip_contiguous_intersections": boundary_sens["intersection_controls"],
            "same_ring_taurus_candidate": boundary_sens["same_ring_taurus_candidate"],
            "virgo_suffix_control": boundary_sens["virgo_suffix_control"],
        },
        "pigment_roi_crop_path": str(q13_crop_path),
        "quire13_pigment_measurements": pigment_results,
        "historical_comparators": [
            {
                "witness": "Cambridge, Gonville & Caius MS 336/725 (f128v, f158v, ff163r-166v)",
                "role": "Moonbook prognosis by sign phase (beginning vs end of Aries) and table lookup by heading + elapsed time",
                "what_it_establishes": "Distinguishes sign vs phase vs heading-selected quantity; repeated outputs (Cancer 30 / house II Leo 20 at 3 and 7 min) do not invert uniquely.",
                "missing_for_ms408": "No numbered degree cutoff, sign phase, or table heading recovered in MS 408.",
            },
            {
                "witness": "Munich, BSB Cgm 415 (ff326v-328r) & Cgm 7958 (fol. 2v, 15r)",
                "role": "30-degree/60-minute angular units (Cgm 415); cross-marked clockwise volvelle + mod-30 onomancy & 28-mansion table (Cgm 7958)",
                "what_it_establishes": "Attests 30-part zodiac divisions, cross start-markers, and secondary fields separating otherwise identical states.",
                "missing_for_ms408": "No directional arrow, degree rule, mod-30 arithmetic, or mansion-text legend attested in MS 408; Cgm 7958 does not map pigment color to water temperature.",
            },
            {
                "witness": "Morgan Library MS G.74 (ff12r, 21r, 33v-35r)",
                "role": "Illustrated De balneis Puteolanis: pouring to head, tiered baths, and cross/title/verse word-link (*crucis*) vs shared 3-figure-arch motif",
                "what_it_establishes": "Shows how a picture can depict head-directed delivery while text gives bath names/verses, and proves shared visual motifs (ff33v/34v/35r) do not uniquely determine bath identity.",
                "missing_for_ms408": "Quire 13 lacks named site headings or confirmed title-to-verse identity links.",
            },
            {
                "witness": "Celsus, De medicina I.4 (with BML Plut. 73.6 Medici witness)",
                "role": "Historical positive control for cold-water head conduit / hot-tepid-cold affusion",
                "what_it_establishes": "Provides a classical precedent for cold water applied specifically to the head beneath a conduit.",
                "missing_for_ms408": "Does not depict f75v's 10-crown geometry, does not key pigment color to temperature, and has no established manuscript bridge to MS 408.",
            },
        ],
    }


def main() -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    CROPS_DIR.mkdir(parents=True, exist_ok=True)

    task1 = run_task1()
    task2 = run_task2()
    task3 = run_task3()

    reg = {
        "schema_version": 1,
        "join": "join3_zodiac_visual",
        "title": "Zodiac Visual-Selector Registration & Quire 13 Anchor",
        "scientific_framing": "MS 408 is not a cipher; visual features and chip groups are analyzed structurally without cipher-key assumptions or ungrounded botanical/medical translations.",
        "task1_pixel_polar_registration": task1,
        "task2_whole_panel_and_controls": task2,
        "task3_quire13_zodiac_audit": task3,
    }

    reg_path = OUT_DIR / "REGISTRATION.json"
    reg_path.write_text(json.dumps(reg, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    # Verify all PNG crops open cleanly
    crop_files = sorted(CROPS_DIR.glob("*.png"))
    verified_crops = []
    for cp in crop_files:
        with Image.open(cp) as im:
            im.verify()
        with Image.open(cp) as im2:
            w, h = im2.size
        verified_crops.append({"path": str(cp), "size_wh": [w, h]})

    print(json.dumps({
        "registration_json": str(reg_path),
        "panels_registered": len(task1["panels"]),
        "crops_verified": verified_crops,
        "q13_faces_audited": len(task3["quire13_per_face"]),
        "q13_totals": task3["quire13_20face_summary"],
    }, indent=2))


if __name__ == "__main__":
    main()
