#!/usr/bin/env python3
"""Join 1: f66r/f39v/f104r Role & Short-Sign Binding.

Deterministic read-only analysis script for
`../../../resources/tools/provenance/index.html#s-c16740c574dc7157`.
Reads only existing research packets, corpus indices, and mounted panel files;
writes ONLY inside its own join directory (`ANALYSIS.json` and `RECEIPT.json`).
"""

from __future__ import annotations

import hashlib
import json
import re
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

ROOT = Path("../../../resources/readers/provenance/source-ebe21fd8a5d0b4c3.html")
JOIN_DIR = Path(__file__).resolve().parent.parent
RESEARCH = ROOT / "research"
F66R_DIR = RESEARCH / "f66r_comparators_2026-11-25"
CHEODAL_DIR = F66R_DIR / "cheodal_return_2026-11-27"
REL_DIR = F66R_DIR / "relationship_test"
YTEDY_DIR = RESEARCH / "ytedy_return_fields_2026-11-27"
PAGES_DIR = ROOT / "CHIP_READER" / "data" / "pages"
STOLFI_PATH = ROOT / "analysis" / "transcriptions" / "stolfi_inter.evt"


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()


class InputTracker:
    """Pins SHA-256 hashes of all read-only source inputs."""

    def __init__(self) -> None:
        self.pins: dict[str, dict[str, Any]] = {}

    def pin(self, path: Path) -> Path:
        key = str(path)
        if key not in self.pins:
            self.pins[key] = {
                "bytes": path.stat().st_size,
                "sha256": sha256_file(path),
            }
        return path

    def load_json(self, path: Path) -> Any:
        return json.loads(self.pin(path).read_text(encoding="utf-8"))

    def load_text(self, path: Path, encoding: str = "utf-8") -> str:
        return self.pin(path).read_text(encoding=encoding)


def load_mounted_panels(tracker: InputTracker) -> tuple[dict[str, dict[str, Any]], dict[str, str]]:
    pages: dict[str, dict[str, Any]] = {}
    folio_section: dict[str, str] = {}
    for p in sorted(PAGES_DIR.glob("*.js")):
        if p.name == "index.js":
            continue
        raw = tracker.load_text(p)
        payload = raw.split("=", 1)[1].strip().rstrip(";")
        data = json.loads(payload)
        folio = data["folio"]
        pages[folio] = data
        folio_section[folio] = data["section"]
    return pages, folio_section


def flatten_unit(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
    flat: list[dict[str, Any]] = []
    unit_pos = 0
    for li, line in enumerate(lines, 1):
        for gi, g in enumerate(line["groups"], 1):
            unit_pos += 1
            flat.append({
                "unit_pos": unit_pos,
                "line_index": li,
                "locus": line["id"],
                "group_in_line": gi,
                "raw": g["raw"],
                "form": g.get("form"),
                "ops": g.get("ops"),
                "uncertain": bool(g.get("uncertain")),
                "source_status": g.get("source_status"),
            })
    return flat


def analyze_corpus_inventory(
    pages: dict[str, dict[str, Any]],
    corpus_index: dict[str, Any],
) -> dict[str, Any]:
    """Exhaustive census of (>=3 okar + >=1 okal) / cheodal+(okar|okal) & -o-d-a-l."""
    matching_paragraphs = []
    matching_nonpar = []
    odal_records = []
    odal_by_para: Counter[tuple[str, str | None]] = Counter()
    odal_forms: Counter[str] = Counter()

    for folio, pdata in sorted(pages.items()):
        section = pdata["section"]
        by_par: dict[str, list[dict[str, Any]]] = defaultdict(list)
        for line in pdata["lines"]:
            par = line.get("paragraph")
            key = par if par else f"NONPAR:{folio}:{line.get('register')}"
            by_par[key].append(line)

        for key, lines in sorted(by_par.items()):
            gs = [g for l in lines for g in l["groups"]]
            exact_okar = sum(1 for g in gs if g.get("form") == "okar" and not g.get("uncertain"))
            all_okar = sum(1 for g in gs if g.get("form") == "okar")
            exact_okal = sum(1 for g in gs if g.get("form") == "okal" and not g.get("uncertain"))
            all_okal = sum(1 for g in gs if g.get("form") == "okal")
            exact_cheodal = sum(1 for g in gs if g.get("form") == "cheodal" and not g.get("uncertain"))
            all_cheodal = sum(1 for g in gs if g.get("form") == "cheodal")
            split_cheodal = 0
            for l in lines:
                lgs = l["groups"]
                for i in range(len(lgs) - 1):
                    if lgs[i].get("form") == "cheo" and lgs[i + 1].get("form") == "dal":
                        split_cheodal += 1

            cond_any = (all_okar >= 3 and all_okal >= 1) or (
                (all_cheodal + split_cheodal) >= 1 and (all_okar + all_okal) >= 1
            )
            if cond_any:
                rec = {
                    "unit": key,
                    "folio": folio,
                    "section": section,
                    "lines": len(lines),
                    "groups": len(gs),
                    "exact_cheodal": exact_cheodal,
                    "all_cheodal": all_cheodal,
                    "split_cheodal": split_cheodal,
                    "exact_okar": exact_okar,
                    "all_okar": all_okar,
                    "exact_okal": exact_okal,
                    "all_okal": all_okal,
                }
                if key.startswith("NONPAR:"):
                    matching_nonpar.append(rec)
                else:
                    matching_paragraphs.append(rec)

        for l in pdata["lines"]:
            for gi, g in enumerate(l["groups"], 1):
                ops = g.get("ops")
                if ops and len(ops) >= 4 and ops[-4:] == ["o", "d", "a", "l"]:
                    form = g.get("form") or g["raw"]
                    odal_forms[form] += 1
                    odal_by_para[(folio, l.get("paragraph"))] += 1
                    odal_records.append({
                        "folio": folio,
                        "section": section,
                        "locus": l["id"],
                        "paragraph": l.get("paragraph"),
                        "register": l.get("register"),
                        "position": gi,
                        "raw": g["raw"],
                        "form": g.get("form"),
                        "prefix_ops": ops[:-4],
                        "uncertain": bool(g.get("uncertain")),
                    })

    index_folios = sorted({u["folio"] for u in corpus_index["units"].values()})
    return {
        "mounted_panel_count": len(pages),
        "corpus_context_index_units": len(corpus_index["units"]),
        "corpus_context_index_folios": len(index_folios),
        "matching_paragraphs_ge3_okar_okal_or_cheodal_okar_okal": matching_paragraphs,
        "matching_nonpar_clusters": matching_nonpar,
        "corpus_odal_tail_total": len(odal_records),
        "corpus_odal_distinct_forms": len(odal_forms),
        "corpus_odal_form_counts": dict(odal_forms.most_common()),
        "paragraphs_with_ge2_odal": [
            {"folio": f, "paragraph": p, "count": c}
            for (f, p), c in sorted(odal_by_para.items(), key=lambda x: (-x[1], x[0][0], str(x[0][1])))
            if c >= 2
        ],
        "f87r_family_external_distributions": {
            form: [r for r in odal_records if r["form"] == form]
            for form in ["oteodal", "cthodal", "teeodal", "cheodal"]
        },
    }


def analyze_task1(
    contexts_data: dict[str, Any],
    returns_data: dict[str, Any],
    pages: dict[str, dict[str, Any]],
    folio_section: dict[str, str],
) -> dict[str, Any]:
    """Complete f39v.P2 vs f104r.P11 comparison, controls, f87r.P1, and f67r2 role test."""
    target_units = ["f39v.P2", "f104r.P11", "f40r.P1", "f55r.P1", "f95r2.P2", "f87r.P1"]
    unit_profiles: dict[str, Any] = {}

    for pid in target_units:
        folio = pid.split(".")[0]
        lines = contexts_data["complete_units"][pid]
        flat = flatten_unit(lines)
        exact_forms = [g["form"] for g in flat if g["form"] and not g["uncertain"]]

        def positions_of(target_form: str, allow_uncertain: bool = False) -> list[dict[str, Any]]:
            out = []
            for g in flat:
                if g["form"] == target_form and (allow_uncertain or not g["uncertain"]):
                    idx = g["unit_pos"] - 1
                    out.append({
                        "unit_pos": g["unit_pos"],
                        "locus": g["locus"],
                        "group_in_line": g["group_in_line"],
                        "raw": g["raw"],
                        "uncertain": g["uncertain"],
                        "left_neighbor": flat[idx - 1]["raw"] if idx > 0 else None,
                        "right_neighbor": flat[idx + 1]["raw"] if idx + 1 < len(flat) else None,
                    })
            return out

        okars = positions_of("okar", allow_uncertain=False)
        okals = positions_of("okal", allow_uncertain=False)
        cheodals = positions_of("cheodal", allow_uncertain=False)

        okar_gaps = []
        for i in range(len(okars) - 1):
            a = okars[i]["unit_pos"] - 1
            b = okars[i + 1]["unit_pos"] - 1
            between = flat[a + 1 : b]
            okar_gaps.append({
                "from_okar_index": i + 1,
                "to_okar_index": i + 2,
                "from_locus": f"{okars[i]['locus']}.{okars[i]['group_in_line']}",
                "to_locus": f"{okars[i + 1]['locus']}.{okars[i + 1]['group_in_line']}",
                "intervening_group_count": len(between),
                "intervening_forms": [x["raw"] for x in between],
                "contains_okal": any(x["form"] == "okal" and not x["uncertain"] for x in between),
                "contains_cheodal": any(x["form"] == "cheodal" and not x["uncertain"] for x in between),
            })

        family_counts = {
            w: sum(1 for g in flat if g["form"] == w and not g["uncertain"])
            for w in ["cheodal", "okar", "okal", "oraly", "ockhy", "ar", "am", "qokar", "qokal", "ykar", "okaiin"]
        }
        odal_members = [
            {
                "unit_pos": g["unit_pos"],
                "locus": g["locus"],
                "group_in_line": g["group_in_line"],
                "raw": g["raw"],
                "prefix_ops": g["ops"][:-4],
                "left_neighbor": flat[g["unit_pos"] - 2]["raw"] if g["unit_pos"] > 1 else None,
                "right_neighbor": flat[g["unit_pos"]]["raw"] if g["unit_pos"] < len(flat) else None,
            }
            for g in flat
            if g["ops"] and len(g["ops"]) >= 4 and g["ops"][-4:] == ["o", "d", "a", "l"]
        ]

        unit_profiles[pid] = {
            "folio": folio,
            "section": folio_section[folio],
            "line_count": len(lines),
            "group_count": len(flat),
            "distinct_exact_forms": sorted(set(exact_forms)),
            "lines": [
                {
                    "id": l["id"],
                    "raw": l["raw"],
                    "groups": [g["raw"] for g in l["groups"]],
                }
                for l in lines
            ],
            "okar_occurrences": okars,
            "okal_occurrences": okals,
            "cheodal_occurrences": cheodals,
            "okar_gaps": okar_gaps,
            "family_counts": family_counts,
            "odal_members": odal_members,
            "sequence_order_signature": [
                {"token": g["form"], "unit_pos": g["unit_pos"], "locus": g["locus"], "group_in_line": g["group_in_line"]}
                for g in flat
                if g["form"] in ("okar", "okal", "cheodal", "oraly") and not g["uncertain"]
            ],
        }

    # Explicit traversal comparison for f39v.P2 using returns_data
    f39_lookup = {
        (g["locus"], g["group_in_line"]): g
        for g in flatten_unit(contexts_data["complete_units"]["f39v.P2"])
    }
    f39_traversals = {}
    for trial in returns_data["explicit_reading_order_controls"]:
        order_name = trial["order"]
        p2_seq = [
            (loc, pos)
            for (loc, pos) in trial["complete_group_order"]
            if (loc, pos) in f39_lookup
        ]
        markers = []
        for idx, (loc, pos) in enumerate(p2_seq, 1):
            g = f39_lookup[(loc, pos)]
            if g["form"] in ("oraly", "okar", "okal", "cheodal", "ockhy", "am") and not g["uncertain"]:
                markers.append({
                    "p2_traversal_pos": idx,
                    "locus": loc,
                    "group_in_line": pos,
                    "form": g["form"],
                })
        f39_traversals[order_name] = {
            "p2_group_count": len(p2_seq),
            "first_following_okar_after_oraly": trial["first_following_okar_after_oraly"],
            "cheodal_after_oraly": trial["cheodal_after_oraly"],
            "okal_echo_relations": trial["okal_echo_relations"],
            "marker_order": markers,
        }

    # Lexical overlap between f39v.P2 and f104r.P11 and pairwise with controls
    s39 = set(unit_profiles["f39v.P2"]["distinct_exact_forms"])
    s104 = set(unit_profiles["f104r.P11"]["distinct_exact_forms"])
    pairwise_overlap = {
        pid: sorted(s39 & set(unit_profiles[pid]["distinct_exact_forms"]))
        for pid in ["f104r.P11", "f40r.P1", "f55r.P1", "f95r2.P2", "f87r.P1"]
    }

    # Test f104r.P11 and f87r.P1 against all 12 f67r2 sectors
    f67r2_sectors = returns_data["all12_return_field_inventory"]
    f104_vs_f67r2 = []
    f87_odal_forms = {m["raw"] for m in unit_profiles["f87r.P1"]["odal_members"]}
    f87_vs_f67r2 = []
    for sec in f67r2_sectors:
        sec_num = sec["sector"]
        by_field = {}
        all_sec_forms = set()
        for fname in ["outer", "figure_field", "detached_field", "body"]:
            forms = [g["form"] for l in sec[fname] for g in l["groups"] if g.get("form") and not g.get("uncertain")]
            by_field[fname] = forms
            all_sec_forms.update(forms)
        hits_104 = sorted(all_sec_forms & s104)
        hits_87_odal = sorted(all_sec_forms & f87_odal_forms)
        if hits_104:
            f104_vs_f67r2.append({
                "sector": sec_num,
                "outer_loci": [l["id"] for l in sec["outer"]],
                "shared_forms": hits_104,
                "matched_fields": {k: [x for x in v if x in s104] for k, v in by_field.items() if any(x in s104 for x in v)},
            })
        if hits_87_odal:
            f87_vs_f67r2.append({"sector": sec_num, "shared_odal": hits_87_odal})

    # Also test f104r.P11's immediate okar followers (qopchar, oraiin, oteody) on f67r2
    f104_okar_followers = [x["right_neighbor"] for x in unit_profiles["f104r.P11"]["okar_occurrences"]]
    f67r2_all_exact = {
        g["form"]
        for l in pages["f67r2"]["lines"]
        for g in l["groups"]
        if g.get("form") and not g.get("uncertain")
    }
    f104_follower_hits_on_f67r2 = [w for w in f104_okar_followers if w in f67r2_all_exact]

    # Summarize all 12 f67r2 sectors' return fields
    f67r2_inventory = [
        {
            "sector": sec["sector"],
            "outer_loci": [l["id"] for l in sec["outer"]],
            "outer_groups": [g["raw"] for l in sec["outer"] for g in l["groups"]],
            "figure_field_loci": [l["id"] for l in sec["figure_field"]],
            "figure_field_groups": [g["raw"] for l in sec["figure_field"] for g in l["groups"]],
            "detached_field_loci": [l["id"] for l in sec["detached_field"]],
            "detached_field_groups": [g["raw"] for l in sec["detached_field"] for g in l["groups"]],
            "body_loci": [l["id"] for l in sec["body"]],
            "body_group_count": sum(len(l["groups"]) for l in sec["body"]),
        }
        for sec in f67r2_sectors
    ]

    return {
        "unit_profiles": unit_profiles,
        "f39v_p2_traversals": f39_traversals,
        "f39v_p2_shared_forms_with_other_units": pairwise_overlap,
        "f104r_p11_okar_followers": f104_okar_followers,
        "f104r_p11_follower_hits_on_f67r2": f104_follower_hits_on_f67r2,
        "f104r_p11_all_hits_on_f67r2_sectors": f104_vs_f67r2,
        "f87r_p1_odal_hits_on_f67r2_sectors": f87_vs_f67r2,
        "f67r2_12_sector_inventory": f67r2_inventory,
        "role_and_scope_verdict": {
            "assigns_source_scope": False,
            "assigns_receiving_field_role": False,
            "discriminates_entry_4_vs_11": False,
            "reasons": [
                "f39v.P2 and f104r.P11 share the exact inventory {1 cheodal, 3 okar, 1 okal} and a 1-group okar.X.okar pair (am vs oraiin), yet reverse the order of okal vs cheodal and place cheodal after all 3 okar in f39v.P2 vs after 1 and before 2 okar in f104r.P11.",
                "Only 4 exact groups overlap between f39v.P2 (73 groups) and f104r.P11 (25 groups): {cheodal, okaiin, okal, okar}.",
                "Three corpus-wide controls (f40r.P1, f55r.P1, f95r2.P2) share >=3 okar + >=1 okal without cheodal and place okal before all okar (f40r.P1), after all okar (f55r.P1), or both before and between okar (f95r2.P2).",
                "f104r.P11 okar followers (qopchar, oraiin, oteody) produce 0 hits across all 12 f67r2 sectors.",
                "f87r.P1 contains the unique 4-member -o-d-a-l family (oteodal, cthodal, y,teeodal, cheodal) with 0 okar and 0 okal, decoupling -o-d-a-l prefix variation from the okar/okal environment.",
            ],
        },
    }


def analyze_task2(
    f66r_data: dict[str, Any],
    margin_tsv_text: str,
    fields_data: dict[str, Any],
    receivers_data: dict[str, Any],
    returns_data: dict[str, Any],
    pages: dict[str, dict[str, Any]],
    folio_section: dict[str, str],
) -> dict[str, Any]:
    """f66r 15-entry & 34-short-sign discriminator audit + f66r vs f67r2 comparison."""
    tsv_lines = [line.split("\t") for line in margin_tsv_text.strip().splitlines()]
    tsv_header = tsv_lines[0]
    tsv_rows = tsv_lines[1:]

    # Build lookup of all 34 short signs from fields_data
    sign_records = []
    sign_by_locus: dict[str, dict[str, Any]] = {}
    assigned_sign_loci_to_rows: dict[str, list[str]] = defaultdict(list)
    for row in f66r_data["rows"]:
        for sl in row["single_sign_loci"]:
            assigned_sign_loci_to_rows[sl].append(row["margin_locus"])

    for s in fields_data["sign_to_line"]:
        loc = s["sign_locus"]
        rec = {
            "sign_locus": loc,
            "sign_raw": s["sign_raw"],
            "form": s["group"].get("form"),
            "ops": s["group"].get("ops"),
            "source_status": s["group"].get("source_status"),
            "sign_y": s["sign_y"],
            "nearest_body": s["nearest_body"],
            "alternatives_10px": s["alternatives"],
            "assigned_margin_loci": assigned_sign_loci_to_rows.get(loc, []),
        }
        sign_records.append(rec)
        sign_by_locus[loc] = rec

    unassigned_short_signs = [r for r in sign_records if not r["assigned_margin_loci"]]
    shared_short_signs = [r for r in sign_records if len(r["assigned_margin_loci"]) > 1]

    # Body lines covered vs omitted by outer-entry body_loci
    all_body_loci = [l["id"] for p in f66r_data["paragraphs"] for l in p["lines"]]
    assigned_body_loci: dict[str, list[str]] = defaultdict(list)
    for row in f66r_data["rows"]:
        for bl in row["body_loci"]:
            assigned_body_loci[bl].append(row["margin_locus"])
    unassigned_body_loci = [bl for bl in all_body_loci if bl not in assigned_body_loci]

    # Build 15-entry audit records
    entries = []
    upper_entries = []
    bottom_entries = []
    for idx, row in enumerate(f66r_data["rows"], 1):
        og = row["outer_group"]
        ops = og["ops"]
        ext_occs = [occ for occ in row["corpus_occurrences"] if occ["folio"] != "f66r"]
        sec_counts = Counter(folio_section[occ["folio"]] for occ in ext_occs)
        reg_counts = Counter(occ["register"] for occ in ext_occs)
        trim_interior = ops[1:-1] if len(ops) > 2 else []
        band = "bottom_6" if idx >= 10 else "upper_9"
        rec = {
            "entry_index": idx,
            "band": band,
            "margin_locus": row["margin_locus"],
            "raw": row["margin_raw"],
            "mounted_form": og["form"],
            "uncertain": bool(og["uncertain"]),
            "ops": ops,
            "chip_length": len(ops),
            "opener": ops[0],
            "ending": ops[-1],
            "trim_interior_ops": trim_interior,
            "baseline_y": row["baseline_y"],
            "nearest_body_locus": row["nearest_body_locus"],
            "nearest_body_distance_px": row["nearest_body_distance_px"],
            "body_loci": row["body_loci"],
            "short_sign_loci": row["single_sign_loci"],
            "short_sign_raw": row["single_sign_raw"],
            "short_sign_ops_list": [sign_by_locus[sl]["ops"] for sl in row["single_sign_loci"]],
            "body_exact_occurrences_f66r": list(row["whole_body_exact_matches"]),
            "corpus_total_occurrences": len(row["corpus_occurrences"]),
            "external_occurrence_count": len(ext_occs),
            "external_folio_count": len(row["external_folios"]),
            "external_folios": row["external_folios"],
            "external_section_counts": dict(sorted(sec_counts.items())),
            "external_register_counts": dict(sorted(reg_counts.items())),
        }
        entries.append(rec)
        if band == "bottom_6":
            bottom_entries.append(rec)
        else:
            upper_entries.append(rec)

    # Vertical baseline spacings
    outer_ys = [e["baseline_y"] for e in entries]
    outer_dys = [outer_ys[i + 1] - outer_ys[i] for i in range(len(outer_ys) - 1)]
    body_ys = fields_data["coordinates"]["body_y"]
    body_dys = [
        {
            "from": all_body_loci[i],
            "to": all_body_loci[i + 1],
            "dy_px": body_ys[i + 1] - body_ys[i],
        }
        for i in range(len(all_body_loci) - 1)
    ]

    # Short signs split across Upper 9 (.16-.36, 21 loci) vs Bottom 6 (.37-.49, 13 loci)
    upper_signs = [s for s in sign_records if int(s["sign_locus"].split(".")[1]) <= 36]
    bottom_signs = [s for s in sign_records if int(s["sign_locus"].split(".")[1]) >= 37]
    upper_sign_tokens = Counter(s["sign_raw"].split("<!")[0] for s in upper_signs)
    bottom_sign_tokens = Counter(s["sign_raw"].split("<!")[0] for s in bottom_signs)

    # Discriminator comparison Upper 9 vs Bottom 6
    def summarize_band(band_entries: list[dict[str, Any]], band_signs: list[dict[str, Any]]) -> dict[str, Any]:
        return {
            "entry_count": len(band_entries),
            "chip_lengths": [e["chip_length"] for e in band_entries],
            "mean_chip_length": round(sum(e["chip_length"] for e in band_entries) / len(band_entries), 4),
            "openers": dict(Counter(e["opener"] for e in band_entries)),
            "endings": dict(Counter(e["ending"] for e in band_entries)),
            "hapax_external_zero_count": sum(1 for e in band_entries if e["external_occurrence_count"] == 0),
            "external_sections_present": sorted({
                sec for e in band_entries for sec in e["external_section_counts"]
            }),
            "short_sign_count": len(band_signs),
            "short_sign_token_counts": dict(Counter(s["sign_raw"].split("<!")[0] for s in band_signs)),
            "unparsed_or_nonalphabetic_signs": [
                s["sign_locus"] + ":" + s["sign_raw"].split("<!")[0]
                for s in band_signs
                if s["ops"] is None
            ],
        }

    upper_summary = summarize_band(upper_entries, upper_signs)
    bottom_summary = summarize_band(bottom_entries, bottom_signs)
    shared_sign_tokens = sorted(set(upper_sign_tokens) & set(bottom_sign_tokens))
    upper_only_sign_tokens = sorted(set(upper_sign_tokens) - set(bottom_sign_tokens))
    bottom_only_sign_tokens = sorted(set(bottom_sign_tokens) - set(upper_sign_tokens))

    # f66r outer vs f67r2 outer & ykaly comparison
    f66_outer_forms = [e["mounted_form"] for e in entries]
    f67_outer_all = []
    for sec in returns_data["all12_return_field_inventory"]:
        for l in sec["outer"]:
            for g in l["groups"]:
                f67_outer_all.append({
                    "sector": sec["sector"],
                    "locus": l["id"],
                    "raw": g["raw"],
                    "form": g.get("form"),
                    "uncertain": bool(g.get("uncertain")),
                })
    f67_outer_exact = [x["form"] for x in f67_outer_all if x["form"] and not x["uncertain"]]
    outer_overlap_f66_f67 = sorted(set(f66_outer_forms) & set(f67_outer_exact))

    f66_all_exact = {
        g["form"]
        for l in pages["f66r"]["lines"]
        for g in l["groups"]
        if g.get("form") and not g.get("uncertain")
    }
    f67_all_exact = {
        g["form"]
        for l in pages["f67r2"]["lines"]
        for g in l["groups"]
        if g.get("form") and not g.get("uncertain")
    }

    # All 7 current ykaly occurrences with section
    ykaly_occ = []
    for occ in receivers_data["all_seven_occurrences"]:
        ykaly_occ.append({
            "folio": occ["folio"],
            "section": folio_section[occ["folio"]],
            "locus": occ["target"]["locus"],
            "register": occ["line"]["register"],
            "line_raw": occ["line"]["raw"],
        })

    return {
        "margin_tsv_row_count": len(tsv_rows),
        "margin_tsv_columns": tsv_header,
        "entries": entries,
        "short_signs_all_34": sign_records,
        "unassigned_short_signs": [
            {"sign_locus": s["sign_locus"], "sign_raw": s["sign_raw"], "nearest_body": s["nearest_body"]}
            for s in unassigned_short_signs
        ],
        "boundary_shared_short_signs": [
            {"sign_locus": s["sign_locus"], "sign_raw": s["sign_raw"], "assigned_margin_loci": s["assigned_margin_loci"]}
            for s in shared_short_signs
        ],
        "unassigned_body_loci": unassigned_body_loci,
        "vertical_geometry": {
            "outer_baseline_ys": outer_ys,
            "outer_consecutive_dy_px": outer_dys,
            "upper_9_dy_range_px": [min(outer_dys[:8]), max(outer_dys[:8])],
            "upper_to_bottom_boundary_dy_px": outer_dys[8],
            "bottom_6_dy_range_px": [min(outer_dys[9:]), max(outer_dys[9:])],
            "body_consecutive_dy_px": body_dys,
            "paragraph_gaps_dy_px": {
                "P1_to_P2_f66r.56_to_57": body_ys[7] - body_ys[6],
                "P2_to_P3_f66r.62_to_63": body_ys[13] - body_ys[12],
                "P3_to_P4_f66r.66_to_67": body_ys[17] - body_ys[16],
                "P4_to_P5_f66r.69_to_70": body_ys[20] - body_ys[19],
            },
        },
        "upper_9_vs_bottom_6": {
            "upper_9": upper_summary,
            "bottom_6": bottom_summary,
            "shared_short_sign_tokens": shared_sign_tokens,
            "upper_only_short_sign_tokens": upper_only_sign_tokens,
            "bottom_only_short_sign_tokens": bottom_only_sign_tokens,
            "discriminator_verdict": {
                "separated_by_paragraph_and_pair_continuity": True,
                "separated_by_chip_length": False,
                "separated_by_opener_or_ending": False,
                "separated_by_external_section_profile": False,
                "asymmetric_short_sign_vocabulary": True,
                "note": "Bottom 6 occupy one continuous 12-line paragraph (P5) with complete alternate-row pairing and all 13 adjacent short signs attached (including both @-glyphs @172; and @195;), whereas Upper 9 span P1-P4 across wide paragraph breaks leaving 8 prose lines and 2 'f' signs (.31, .36) outside local windows. Neither chip length, opener/ending, nor external section profile separates the two bands.",
            },
        },
        "f66r_vs_f67r2_comparison": {
            "f66r_outer_count": len(f66_outer_forms),
            "f67r2_outer_sector_count": 12,
            "f67r2_outer_group_count": len(f67_outer_all),
            "f67r2_outer_group_counts_per_sector": dict(Counter(
                sum(len(l["groups"]) for l in sec["outer"])
                for sec in returns_data["all12_return_field_inventory"]
            )),
            "exact_outer_overlap": outer_overlap_f66_f67,
            "f67r2_outer_forms_in_f66r_any_register": sorted(set(f67_outer_exact) & f66_all_exact),
            "f66r_outer_forms_in_f67r2_any_register": sorted(set(f66_outer_forms) & f67_all_exact),
            "ykaly_all_seven_corpus_occurrences": ykaly_occ,
            "ykaly_f66r10_vs_f67r2_9": {
                "f66r_10": {
                    "carrier": "isolated 1-group outer entry beside prose",
                    "short_signs": ["f66r.37:c", "f66r.38:@172;"],
                    "candidate_body": "f66r.70-71 (21 groups)",
                    "standalone_kal_in_candidate": 1,
                    "embedded_kal_in_P5": ["kal(.71)", "qokaly(.76)", "qokal(.77)", "okalchedy(.79)", "shekaly(.81)"],
                },
                "f67r2_9": {
                    "sector": 10,
                    "carrier": "2-group outer wheel sector header: ykar.ykaly",
                    "short_signs": [],
                    "detached_field": [],
                    "figure_field": ["f67r2.60:octhys"],
                    "candidate_body": "f67r2.38-40 (8 groups)",
                    "standalone_kal_on_page": 0,
                    "embedded_kal_in_sector_body_or_figure": 0,
                },
            },
        },
    }


def collect_predecessor_findings(
    f66r_data: dict[str, Any],
    returns_data: dict[str, Any],
    contexts_data: dict[str, Any],
    fields_data: dict[str, Any],
    controls_data: dict[str, Any],
    stolfi_text: str,
) -> dict[str, Any]:
    """Verify and preserve all predecessor findings and older boundary/letter variants."""
    focal_patterns = [
        r"^<f39v\.P\.(7|9|12);",
        r"^<f67r2\.(L|X|Y)\.(4|10|11);",
        r"^<f67v2\.R\.7;",
        r"^<f66r\.R\.22;",
        r"^<f66r\.R\.4;",
        r"^<f87r\.P\.(7|9a);",
        r"^<f114r\.(P1\.33|T1\.34);",
    ]
    stolfi_witnesses = []
    for line_no, line in enumerate(stolfi_text.splitlines(), 1):
        if any(re.match(pat, line) for pat in focal_patterns):
            stolfi_witnesses.append({"source_line": line_no, "record": line})

    return {
        "first_following_okar_after_oraly_convergence": {
            "sector_selected_by_order": {
                t["order"]: t["first_following_okar_after_oraly"]
                for t in returns_data["explicit_reading_order_controls"]
            },
            "all_converge_on_entry_4": all(
                t["first_following_okar_after_oraly"]["sector"] == 4
                for t in returns_data["explicit_reading_order_controls"]
            ),
        },
        "order_sensitive_okal_echo": {
            "source_locus": "f39v.9 right",
            "detached_sector": 4,
            "detached_form": "okal",
            "relations_by_order": {
                t["order"]: t["okal_echo_relations"]
                for t in returns_data["explicit_reading_order_controls"]
            },
        },
        "entry_11_absent_detached_field": {
            "sector": 11,
            "outer_locus": "f67r2.10",
            "figure_field": [g["raw"] for l in returns_data["all12_return_field_inventory"][10]["figure_field"] for g in l["groups"]],
            "detached_field": returns_data["all12_return_field_inventory"][10]["detached_field"],
            "all_sectors_missing_detached": [
                s["sector"] for s in returns_data["all12_return_field_inventory"] if not s["detached_available"]
            ],
        },
        "f66r_39_negative_circinus_control": {
            "locus": "f66r.39",
            "raw": next(s["sign_raw"] for s in fields_data["sign_to_line"] if s["sign_locus"] == "f66r.39"),
            "adjacent_margin_entry": "f66r.11 (doly)",
            "comparator": "Hartlieb Cgm 7958, f23v Circinus legend",
            "verdict": "NEGATIVE_SHAPE_CONTROL — Cgm 7958 compass has crossbar crossing both legs; f66r.39 has cap and dividing stem beneath it.",
        },
        "f66r_inherited_counts": f66r_data["counts"],
        "f66r_last_six_repeat_control": {
            "repeated_in_own_candidate_pair": controls_data["f66r_last_six_labels_repeated_in_candidate_pair"],
            "ykaly_body_count": controls_data["f66r_ykaly_body_count"],
        },
        "older_edition_boundary_and_letter_variants": {
            "notes": returns_data["older_relation_notes"],
            "context_variant_notes": contexts_data["older_variant_controls"],
            "stolfi_witness_lines": stolfi_witnesses,
        },
    }


def run_assertions(analysis: dict[str, Any]) -> list[dict[str, Any]]:
    t1 = analysis["task1_f39v_vs_f104r"]
    t2 = analysis["task2_f66r_audit"]
    inv = analysis["corpus_inventory"]
    pred = analysis["predecessor_preserved"]

    checks = [
        ("mounted_panels_227", inv["mounted_panel_count"] == 227),
        ("corpus_context_index_227_folios", inv["corpus_context_index_folios"] == 227),
        ("exact_5_corpus_paragraphs_match_okar_okal_or_cheodal_okar_okal",
         len(inv["matching_paragraphs_ge3_okar_okal_or_cheodal_okar_okal"]) == 5),
        ("f39v_p2_and_f104r_p11_both_1_3_1",
         all(
             t1["unit_profiles"][p]["family_counts"]["cheodal"] == 1
             and t1["unit_profiles"][p]["family_counts"]["okar"] == 3
             and t1["unit_profiles"][p]["family_counts"]["okal"] == 1
             for p in ("f39v.P2", "f104r.P11")
         )),
        ("f39v_p2_and_f104r_p11_share_only_4_forms",
         t1["f39v_p2_shared_forms_with_other_units"]["f104r.P11"] == ["cheodal", "okaiin", "okal", "okar"]),
        ("f104r_p11_okar_followers_zero_hits_on_f67r2",
         len(t1["f104r_p11_follower_hits_on_f67r2"]) == 0),
        ("f87r_p1_unique_4_member_odal_paragraph",
         len(t1["unit_profiles"]["f87r.P1"]["odal_members"]) == 4
         and inv["paragraphs_with_ge2_odal"][0] == {"folio": "f87r", "paragraph": "f87r.P1", "count": 4}),
        ("f66r_15_entries_34_short_signs_32_body_lines",
         len(t2["entries"]) == 15 and len(t2["short_signs_all_34"]) == 34 and len(t2["unassigned_short_signs"]) == 2),
        ("f66r_vs_f67r2_outer_only_ykaly",
         t2["f66r_vs_f67r2_comparison"]["exact_outer_overlap"] == ["ykaly"]),
        ("predecessor_first_following_converges_entry_4",
         pred["first_following_okar_after_oraly_convergence"]["all_converge_on_entry_4"] is True),
        ("predecessor_entry_11_no_detached_field",
         pred["entry_11_absent_detached_field"]["detached_field"] == []
         and pred["entry_11_absent_detached_field"]["all_sectors_missing_detached"] == [1, 3, 5, 10, 11]),
    ]
    return [{"name": k, "passed": bool(v)} for k, v in checks]


def write_receipt(checks: list[dict[str, Any]]) -> None:
    deliverables = {}
    for p in sorted(JOIN_DIR.rglob("*")):
        if not p.is_file() or p.name == "RECEIPT.json":
            continue
        if "__pycache__" in p.parts:
            continue
        rel = str(p.relative_to(JOIN_DIR))
        deliverables[rel] = {
            "bytes": p.stat().st_size,
            "sha256": sha256_file(p),
        }
    receipt = {
        "join_id": "join1_f66r_cheodal",
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "overall_status": "PASS" if all(c["passed"] for c in checks) else "FAIL",
        "checks": checks,
        "deliverables": deliverables,
    }
    (JOIN_DIR / "RECEIPT.json").write_text(
        json.dumps(receipt, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )


def main() -> None:
    tracker = InputTracker()

    # Pin prose reports referenced in prompt
    for rel_md in [
        F66R_DIR / "RESULT.md",
        CHEODAL_DIR / "RESULT.md",
        CHEODAL_DIR / "contexts" / "REPORT.md",
        CHEODAL_DIR / "returns" / "REPORT.md",
        REL_DIR / "RESULT.md",
    ]:
        tracker.pin(rel_md)

    margin_tsv_text = tracker.load_text(F66R_DIR / "analysis" / "MARGIN_TABLE.tsv")
    f66r_data = tracker.load_json(F66R_DIR / "analysis" / "DATA.json")
    controls_data = tracker.load_json(F66R_DIR / "comparators" / "CONTROLS.json")
    contexts_data = tracker.load_json(CHEODAL_DIR / "contexts" / "DATA.json")
    returns_data = tracker.load_json(CHEODAL_DIR / "returns" / "DATA.json")
    fields_data = tracker.load_json(REL_DIR / "fields" / "DATA.json")
    receivers_data = tracker.load_json(REL_DIR / "receivers" / "DATA.json")
    corpus_index = tracker.load_json(YTEDY_DIR / "analysis" / "CORPUS_CONTEXT_INDEX.json")
    stolfi_text = tracker.load_text(STOLFI_PATH, encoding="latin1")
    pages, folio_section = load_mounted_panels(tracker)

    corpus_inventory = analyze_corpus_inventory(pages, corpus_index)
    task1 = analyze_task1(contexts_data, returns_data, pages, folio_section)
    task2 = analyze_task2(
        f66r_data, margin_tsv_text, fields_data, receivers_data, returns_data, pages, folio_section
    )
    predecessor = collect_predecessor_findings(
        f66r_data, returns_data, contexts_data, fields_data, controls_data, stolfi_text
    )

    analysis = {
        "join_id": "join1_f66r_cheodal",
        "title": "Join 1: f66r/f39v/f104r Role & Short-Sign Binding",
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "scientific_framing": {
            "not_a_cipher": True,
            "images_information_bearing": True,
            "historical_comparators_separate_from_ms408_claims": True,
            "stop_list_respected": True,
        },
        "corpus_inventory": corpus_inventory,
        "task1_f39v_vs_f104r": task1,
        "task2_f66r_audit": task2,
        "predecessor_preserved": predecessor,
        "input_pins_count": len(tracker.pins),
        "input_pins": tracker.pins,
    }

    checks = run_assertions(analysis)
    analysis["checks"] = checks
    assert all(c["passed"] for c in checks), f"Checks failed: {checks}"

    (JOIN_DIR / "ANALYSIS.json").write_text(
        json.dumps(analysis, indent=2, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )
    write_receipt(checks)
    print(json.dumps({
        "status": "OK",
        "checks_passed": sum(1 for c in checks if c["passed"]),
        "checks_total": len(checks),
        "input_pins_count": len(tracker.pins),
        "output_analysis": str(JOIN_DIR / "ANALYSIS.json"),
    }, indent=2))


if __name__ == "__main__":
    main()
