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

Mechanical pre-pass for the full-manuscript author-attribution sweep.
Scans every lattice file in ../../../resources/readers/provenance/source-67a34d1930f7dad1.html and
classifies each folio's structural type so the right attribution method
applies (cycle / tier-label / operations-table / continuous-text).

Produces: 176a6aa2009492dc314a07e5.tsv
"""
import os
import re
import sys
from pathlib import Path

LATTICE_DIR = Path("../../../resources/readers/provenance/source-67a34d1930f7dad1.html")
OUT_TSV = Path("176a6aa2009492dc314a07e5.tsv")

# Cycle-marker family in IVTFF (the @169..@172 family seen on f57v.3)
CYCLE_MARKER_RE = re.compile(r"@(169|170|171|172)\b")
# All special chars (any @<int>)
SPECIAL_CHAR_RE = re.compile(r"@\d+")
# Tier-label tokens captured in lattice headers as `(`@Lx`)`-style markers
TIER_LABEL_RE = re.compile(r"\(`(@L0|@Ro|@Lz|&Lz|@Lx|\+Lx|@Cc|\+Cc|\+P0|=P0|@Lc|@Pb)`\)")
# Period-17 cycle structure heuristic: presence of repeated @169..@172 sequence
# (the f57v.3 footprint) is unambiguous; weaker signal is multiple @17X markers.
LINE_HEADER_RE = re.compile(r"^### `(f[0-9rvA-Z]+\.\d+)` \[(\w+(?:-\w+)?)\] \(`([^`]+)`\)")

def classify(path: Path) -> dict:
    text = path.read_text(errors="replace")
    folio = path.stem
    cycle_markers = CYCLE_MARKER_RE.findall(text)
    cycle_marker_count = len(cycle_markers)
    special_chars = SPECIAL_CHAR_RE.findall(text)
    special_char_count = len(special_chars)
    tier_labels = TIER_LABEL_RE.findall(text)
    # tier counts
    tier_counts = {}
    for tl in tier_labels:
        tier_counts[tl] = tier_counts.get(tl, 0) + 1
    # line headers
    line_headers = LINE_HEADER_RE.findall(text)
    line_count = len(line_headers)
    line_types = {}
    for _, ltype, _ in line_headers:
        line_types[ltype] = line_types.get(ltype, 0) + 1
    # Total tokens (look for "Total tokens: N")
    m = re.search(r"Total tokens: (\d+)", text)
    total_tokens = int(m.group(1)) if m else None
    # Section
    m = re.search(r"\*\*Section:\*\* `(\w+)`", text)
    section = m.group(1) if m else "unknown"
    # Heuristic classification
    cycle_pairs = cycle_marker_count // 4  # each cycle has 4 markers (169/170/171/172)
    has_period17_cycles = cycle_marker_count >= 8 and cycle_marker_count % 4 == 0
    has_l0_ro = tier_counts.get("@L0", 0) > 0 and tier_counts.get("@Ro", 0) > 0
    has_lz = tier_counts.get("@Lz", 0) > 0 or tier_counts.get("&Lz", 0) > 0
    has_p0 = tier_counts.get("+P0", 0) > 0 or tier_counts.get("=P0", 0) > 0
    has_pb = tier_counts.get("@Pb", 0) > 0
    has_lx = tier_counts.get("@Lx", 0) > 0 or tier_counts.get("+Lx", 0) > 0
    label_count = line_types.get("LABEL", 0)
    paracont_count = line_types.get("para-cont", 0) + line_types.get("paragraph", 0)
    # primary class
    if has_period17_cycles:
        struct_class = "PERIOD17_CYCLE"
    elif has_l0_ro:
        struct_class = "L0_RO_TIER"
    elif has_lz:
        struct_class = "ZODIAC_LZ"
    elif has_p0:
        struct_class = "OPERATIONS_TABLE_P0"
    elif has_pb:
        struct_class = "ROSETTE_PB"
    elif has_lx:
        struct_class = "MARGINAL_KEY_LX"
    elif label_count > paracont_count and label_count > 3:
        struct_class = "LABEL_HEAVY"
    elif paracont_count > 0:
        struct_class = "CONTINUOUS_TEXT"
    else:
        struct_class = "OTHER"
    return {
        "folio": folio,
        "section": section,
        "struct_class": struct_class,
        "cycle_marker_count": cycle_marker_count,
        "cycle_pairs_estimate": cycle_pairs,
        "special_char_count": special_char_count,
        "tier_L0": tier_counts.get("@L0", 0),
        "tier_Ro": tier_counts.get("@Ro", 0),
        "tier_Lz": tier_counts.get("@Lz", 0) + tier_counts.get("&Lz", 0),
        "tier_P0": tier_counts.get("+P0", 0) + tier_counts.get("=P0", 0),
        "tier_Pb": tier_counts.get("@Pb", 0),
        "tier_Lx": tier_counts.get("@Lx", 0) + tier_counts.get("+Lx", 0),
        "label_lines": label_count,
        "paracont_lines": paracont_count,
        "total_lines": line_count,
        "total_tokens": total_tokens,
    }

def main() -> None:
    files = sorted(LATTICE_DIR.glob("f*.md"))
    rows = [classify(p) for p in files]
    cols = [
        "folio", "section", "struct_class",
        "cycle_marker_count", "cycle_pairs_estimate",
        "special_char_count",
        "tier_L0", "tier_Ro", "tier_Lz", "tier_P0", "tier_Pb", "tier_Lx",
        "label_lines", "paracont_lines", "total_lines", "total_tokens",
    ]
    OUT_TSV.write_text(
        "\t".join(cols) + "\n"
        + "\n".join("\t".join(str(r.get(c, "")) for c in cols) for r in rows)
        + "\n"
    )
    # Class-frequency summary
    classes = {}
    for r in rows:
        classes[r["struct_class"]] = classes.get(r["struct_class"], 0) + 1
    print(f"Classified {len(rows)} folios. Output: {OUT_TSV}")
    print("Structural class distribution:")
    for cls, n in sorted(classes.items(), key=lambda x: -x[1]):
        print(f"  {cls}: {n}")
    # PERIOD17 specifically
    p17 = [r for r in rows if r["struct_class"] == "PERIOD17_CYCLE"]
    if p17:
        print(f"\nPERIOD17_CYCLE folios ({len(p17)}):")
        for r in p17:
            print(f"  {r['folio']}: {r['cycle_pairs_estimate']} cycle-quartets, {r['tier_L0']}xL0 + {r['tier_Ro']}xRo")
    # L0_RO folios
    l0ro = [r for r in rows if r["struct_class"] == "L0_RO_TIER"]
    if l0ro:
        print(f"\nL0_RO_TIER (multi-tier non-cycle) folios ({len(l0ro)}):")
        for r in l0ro:
            print(f"  {r['folio']}: {r['tier_L0']}xL0 + {r['tier_Ro']}xRo, {r['paracont_lines']} para-cont")

if __name__ == "__main__":
    main()
