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

Full-manuscript bulk attribution pass.

For every lattice file:
  1. Extract class-opener frequency (o/l/d/r/v/x/k/m/f/p/t/y/s/c/I/a/e/g)
  2. Extract compound-prefix density (oke, ok, qok, sh, da, ot, ar, ch, she)
  3. Extract terminal density (-aiin, -al, -ar, -ol, -or, -y, -ody, -ldy, -am)
  4. Detect cycle-marker structure
  5. Detect tier-label structure (@L0/@Ro/@Lz/@P0/@Pb/@Lx)
  6. Compute author-attribution signal vector per the training packet

Author-attribution heuristic per training packet Section 4 + bind:
  - **Fontana** (keystone integrated): high I-class anchor density, multi-class
    operator density per line, vessel + oil + decoction + radix all on same line.
  - **Despars** (Italian gen-1 philological): high alpha @Ro density + clean d-class,
    f-class verb register dominant, no I-class keystone anchor.
  - **Albicus** (transalpine collected-categories): clean ok-epsilon @Ro density,
    p-class noun register dominant, recipe-dense.
  - **Hartlieb** (gen-2 vernacular flatten): mixed o-/oke- density, p-class noun,
    chiastic vessel-frame closure (high ot- prefix).
  - **Fusoris-Arnaut** (instrument-frame operations table): high qok-, qot-, ch-,
    daiin density, label-column architecture, no period-17 cycle.

Output: 55d522c69ffa70993e91e354.tsv
"""
import os
import re
from pathlib import Path
from collections import Counter

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

# Class-opener frequency line: "- `o-` (15×) — ..."
CLASS_OPENER_RE = re.compile(r"^\-\s+`(\w+\-?)`\s+\((\d+)×\)", re.MULTILINE)
# Tier-label markers
TIER_LABEL_RE = re.compile(r"\(`(@L0|@Ro|@Lz|&Lz|@Lx|\+Lx|@Cc|\+Cc|\+P0|=P0|@Pb|@P0|\+Pn)`\)")
# Cycle markers
CYCLE_MARKER_RE = re.compile(r"@(169|170|171|172)\b")
# Section
SECTION_RE = re.compile(r"\*\*Section:\*\* `(\w+)`")
# Total tokens
TOKEN_RE = re.compile(r"Total tokens: (\d+)")
# I-class anchor (keystone-integration mark) — substrate marks as `I=herbal-section`
# but the cycle observation calls it the keystone-integration mark
I_KEYSTONE_RE = re.compile(r"\bI\b.*?(?:keystone|standalone|rare|n=1)", re.IGNORECASE)
# Compound prefix markers in chip lines
QOK_RE = re.compile(r"\bqok\b|qok-class|qualified-vessel")
QOT_RE = re.compile(r"qot-|qoteedy|qotey")
OKE_RE = re.compile(r"\boke-\b|ok-epsilon")
OT_RE = re.compile(r"\bot-\b|vessel/container variant")
SH_RE = re.compile(r"\bsh-\b|\bsoak\b")
CH_RE = re.compile(r"\bch-\b|combine-cook|combine/cook")
DAIIN_RE = re.compile(r"\bdaiin\b|ana[\- ]connector")
# Multi-class density per line (count distinct class-opener letters in chip rows)
CHIP_LINE_RE = re.compile(r"^\| `[●★]\w+", re.MULTILINE)

ALPHA_AT_RO_RE = re.compile(r"@Ro\`\)")  # placeholder; computed per-tier-label below


def per_folio_features(text: str) -> dict:
    """Extract feature vector from a single lattice file."""
    section = (SECTION_RE.search(text) or [None, "unknown"]).group(1) \
        if SECTION_RE.search(text) else "unknown"
    total_tokens = int(TOKEN_RE.search(text).group(1)) if TOKEN_RE.search(text) else 0
    # Class-opener frequencies
    openers = {}
    for m in CLASS_OPENER_RE.finditer(text):
        openers[m.group(1)] = int(m.group(2))
    # Tier-label counts
    tier_counts = Counter(m for m in TIER_LABEL_RE.findall(text))
    # Cycle markers
    cycle_count = len(CYCLE_MARKER_RE.findall(text))
    # I-class keystone-integration mark hits (substrate-tagged)
    i_keystone = len(I_KEYSTONE_RE.findall(text))
    # Compound-prefix densities (count occurrences in chip text)
    qok = len(QOK_RE.findall(text))
    qot = len(QOT_RE.findall(text))
    oke = len(OKE_RE.findall(text))
    ot = len(OT_RE.findall(text))
    sh = len(SH_RE.findall(text))
    ch = len(CH_RE.findall(text))
    daiin = len(DAIIN_RE.findall(text))
    # Class-density score per author (heuristic)
    f_count = openers.get("f-", 0)
    p_count = openers.get("p-", 0)
    o_count = openers.get("o-", 0)
    d_count = openers.get("d-", 0)
    r_count = openers.get("r-", 0)
    s_count = openers.get("s-", 0)
    y_count = openers.get("y-", 0)
    c_count = openers.get("c-", 0)
    # Total class openers (for normalisation)
    opener_total = sum(openers.values())
    # Heuristic author-attribution scores
    # Fontana: keystone density × multi-class breadth × vessel+oil+decoction+radix co-occurrence
    fontana_score = (
        i_keystone * 2.0
        + (1 if (o_count > 0 and r_count > 0 and d_count > 0) else 0) * 1.5
        + min(qok / 3.0, 2.0)  # qualified-vessel saturated
        + (cycle_count // 4) * 1.5  # period-17 cycles bonus
    )
    # Despars: f-class verb register dominant + low I-keystone + alpha-class density
    despars_score = (
        (f_count / max(opener_total, 1)) * 4.0
        + (1 if i_keystone == 0 else 0) * 0.5
        + (cycle_count // 4) * 0.7  # cycle but no keystone
    )
    # Albicus: p-class noun register + ok-epsilon + recipe-dense
    albicus_score = (
        (p_count / max(opener_total, 1)) * 4.0
        + min(oke / 3.0, 2.0)
        + (1 if s_count > 0 else 0) * 0.3
    )
    # Hartlieb: p-class + ot- vessel + mixed o/oke
    hartlieb_score = (
        (p_count / max(opener_total, 1)) * 2.5
        + min(ot / 5.0, 2.0)
        + (1 if (oke > 0 and o_count > 0) else 0) * 1.0
    )
    # Fusoris-Arnaut: instrument-frame density (qok + qot + ch + daiin)
    fusoris_arnaut_score = (
        min(qok / 3.0, 2.5)
        + min(qot / 3.0, 2.0)
        + min(ch / 3.0, 1.5)
        + min(daiin / 5.0, 1.5)
    )
    scores = {
        "Fontana": fontana_score,
        "Despars": despars_score,
        "Albicus": albicus_score,
        "Hartlieb": hartlieb_score,
        "Fusoris-Arnaut": fusoris_arnaut_score,
    }
    # Top author + margin
    sorted_scores = sorted(scores.items(), key=lambda x: -x[1])
    top_author, top_score = sorted_scores[0]
    runner_score = sorted_scores[1][1] if len(sorted_scores) > 1 else 0
    margin = top_score - runner_score
    # Decision rule: UNRESOLVED if margin < 0.5 OR top_score < 1.0
    if top_score < 1.0:
        attribution = "UNRESOLVED"
        confidence = "none"
    elif margin < 0.5:
        attribution = f"{top_author}/{sorted_scores[1][0]}"
        confidence = "ambiguous"
    elif margin < 1.5:
        attribution = top_author
        confidence = "low"
    elif margin < 3.0:
        attribution = top_author
        confidence = "medium"
    else:
        attribution = top_author
        confidence = "high"
    return {
        "section": section,
        "total_tokens": total_tokens,
        "opener_total": opener_total,
        "f_count": f_count, "p_count": p_count, "o_count": o_count,
        "d_count": d_count, "r_count": r_count, "y_count": y_count,
        "s_count": s_count, "c_count": c_count,
        "i_keystone": i_keystone,
        "qok": qok, "qot": qot, "oke": oke, "ot": ot,
        "ch": ch, "daiin": daiin,
        "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_counts.get("@P0", 0),
        "tier_Pb": tier_counts.get("@Pb", 0),
        "cycle_marker_count": cycle_count,
        "fontana_s": round(fontana_score, 2),
        "despars_s": round(despars_score, 2),
        "albicus_s": round(albicus_score, 2),
        "hartlieb_s": round(hartlieb_score, 2),
        "fusoris_s": round(fusoris_arnaut_score, 2),
        "attribution": attribution,
        "confidence": confidence,
        "margin": round(margin, 2),
    }


def main() -> None:
    files = sorted(LATTICE_DIR.glob("f*.md"))
    rows = []
    for p in files:
        text = p.read_text(errors="replace")
        feats = per_folio_features(text)
        feats["folio"] = p.stem
        rows.append(feats)
    cols = [
        "folio", "section", "attribution", "confidence", "margin",
        "fontana_s", "despars_s", "albicus_s", "hartlieb_s", "fusoris_s",
        "f_count", "p_count", "o_count", "d_count", "r_count", "y_count",
        "s_count", "c_count", "i_keystone",
        "qok", "qot", "oke", "ot", "ch", "daiin",
        "tier_L0", "tier_Ro", "tier_Lz", "tier_P0", "tier_Pb",
        "cycle_marker_count", "opener_total", "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"
    )
    # Distribution
    attribution_counts = Counter(r["attribution"] for r in rows)
    confidence_counts = Counter(r["confidence"] for r in rows)
    print(f"Attribution pass complete on {len(rows)} folios.")
    print(f"Output: {OUT_TSV}")
    print("\nAttribution distribution:")
    for a, n in sorted(attribution_counts.items(), key=lambda x: -x[1]):
        print(f"  {a}: {n}")
    print("\nConfidence distribution:")
    for c, n in sorted(confidence_counts.items(), key=lambda x: -x[1]):
        print(f"  {c}: {n}")
    # Per-section summary
    print("\nPer-section attribution top-2:")
    section_attribution = {}
    for r in rows:
        section_attribution.setdefault(r["section"], Counter())[r["attribution"]] += 1
    for sec, counts in sorted(section_attribution.items()):
        top2 = counts.most_common(3)
        print(f"  {sec}: {top2}")


if __name__ == "__main__":
    main()
