#!/usr/bin/env python3
"""
folio_currier_hand_overlay_2026-05-07.py

Extracts $L (Currier register A/B) and $H (IVTFF hand 1-5) from every lattice
file's IVTFF header. Overlays these onto the bulk author-attribution TSV from
folio_author_attribution_bulk_2026-05-07.py. Tests the substrate predictions:

  1. Hand 5 should match the Hartlieb-class folios (gen-2 vernacular).
  2. The 6 [d:j] folios (f23r, f47r, f57r, f57v, f72r1, f82r) should cluster on
     Hand 1 if the C1 slot-3 ambiguity is a Fontana handprint.
  3. Currier A folios should skew Italian-corridor (Fontana/Despars).
  4. Currier B folios should skew transalpine (Albicus/Hartlieb).

Output:
  787afe80e4b9fb2dfd7d6e62.tsv
"""
import re
from pathlib import Path
from collections import Counter

LATTICE_DIR = Path("../../../resources/readers/provenance/source-67a34d1930f7dad1.html")
ATTRIB_TSV = Path("55d522c69ffa70993e91e354.tsv")
OUT_TSV = Path("787afe80e4b9fb2dfd7d6e62.tsv")

HEADER_RE = re.compile(r"\*\*IVTFF header:\*\* `<![^>]+>`")
L_RE = re.compile(r"\$L=([A-Z])")
H_RE = re.compile(r"\$H=(\d+)")

def parse_header(text: str) -> dict:
    m = HEADER_RE.search(text)
    if not m:
        return {"currier": "", "hand": ""}
    h = m.group(0)
    l_m = L_RE.search(h)
    h_m = H_RE.search(h)
    return {
        "currier": l_m.group(1) if l_m else "",
        "hand": h_m.group(1) if h_m else "",
    }

def main() -> None:
    # Read existing attribution TSV
    rows = []
    with ATTRIB_TSV.open() as f:
        header = f.readline().rstrip("\n").split("\t")
        for line in f:
            row = dict(zip(header, line.rstrip("\n").split("\t")))
            rows.append(row)
    # Add Currier + Hand from each folio's lattice header
    for r in rows:
        path = LATTICE_DIR / f"{r['folio']}.md"
        if path.exists():
            meta = parse_header(path.read_text(errors="replace"))
            r["currier"] = meta["currier"]
            r["hand"] = meta["hand"]
        else:
            r["currier"] = ""
            r["hand"] = ""
    # Output TSV with new columns
    new_cols = header + ["currier", "hand"]
    OUT_TSV.write_text(
        "\t".join(new_cols) + "\n"
        + "\n".join("\t".join(str(r.get(c, "")) for c in new_cols) for r in rows)
        + "\n"
    )
    # Cross-tab: Hand × Attribution
    print("=" * 70)
    print("CROSS-TAB: Hand × Attribution (mechanical correlation test)")
    print("=" * 70)
    hand_attrib = {}
    for r in rows:
        key = (r["hand"], r["attribution"])
        hand_attrib[key] = hand_attrib.get(key, 0) + 1
    # Print as table
    hands = sorted(set(r["hand"] for r in rows))
    attribs = sorted(set(r["attribution"] for r in rows))
    print(f"\n{'Hand':<6}", end="")
    for a in attribs:
        print(f"{a[:18]:<20}", end="")
    print()
    for h in hands:
        print(f"{h or '(none)':<6}", end="")
        for a in attribs:
            n = hand_attrib.get((h, a), 0)
            print(f"{n:<20}", end="")
        print()
    # Hand 5 specifically
    print("\n" + "=" * 70)
    print("HAND 5 FOLIOS (predicted = Hartlieb-class)")
    print("=" * 70)
    hand5 = [r for r in rows if r["hand"] == "5"]
    for r in hand5:
        print(f"  {r['folio']:<8} | section={r['section']:<8} | attribution={r['attribution']:<30} | hartlieb_s={r['hartlieb_s']}")
    # [d:j] folios
    print("\n" + "=" * 70)
    print("[d:j] FOLIOS (predicted = Hand 1 if Fontana-handprint)")
    print("=" * 70)
    djj_folios = ["f23r", "f47r", "f57r", "f57v", "f72r1", "f82r"]
    for fname in djj_folios:
        r = next((x for x in rows if x["folio"] == fname), None)
        if r:
            print(f"  {fname:<8} | hand={r['hand']:<3} | currier={r['currier']:<3} | attribution={r['attribution']}")
        else:
            print(f"  {fname}: not found")
    # Currier × Attribution
    print("\n" + "=" * 70)
    print("CROSS-TAB: Currier × Attribution")
    print("=" * 70)
    cur_attrib = {}
    for r in rows:
        key = (r["currier"], r["attribution"])
        cur_attrib[key] = cur_attrib.get(key, 0) + 1
    curs = sorted(set(r["currier"] for r in rows))
    print(f"\n{'Cur':<5}", end="")
    for a in attribs:
        print(f"{a[:18]:<20}", end="")
    print()
    for c in curs:
        print(f"{c or '-':<5}", end="")
        for a in attribs:
            n = cur_attrib.get((c, a), 0)
            print(f"{n:<20}", end="")
        print()


if __name__ == "__main__":
    main()
