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

Per-paragraph (per-line) attribution pass within OPERATIONS_TABLE folios.

The bulk per-folio pass averaged out author-level differences because the
operations-table architecture is shared manuscript-wide. Per-paragraph
scoring should detect author-mixing within folios where the page averages
hide author-discriminator signals.

For every line in every lattice file:
  1. Detect class-opener letters in the chip rows (the per-line raw text
     gets parsed into chip rows).
  2. Score the line against author-fingerprints from the bind:
     - Fontana: I-keystone token presence on the line.
     - Despars: f-class verb register without I-keystone, alpha @Ro.
     - Albicus: p-class noun register, ok-epsilon @Ro, recipe-dense.
     - Hartlieb: p-class + ot- + mixed o/oke + chiastic vessel close.
     - Fusoris-Arnaut: qok/qot density + ch-/daiin-heavy operations row.
  3. Output per-line attribution.

Output:
  c5fcf8969fd8385c67e09b86.tsv
  Stats summary printed to stdout.
"""
import re
from pathlib import Path
from collections import Counter

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

# Per-line section-header regex (with line-id, line-type, tier-label)
LINE_HEADER_RE = re.compile(r"^### `(f[0-9rvA-Z]+\.\d+)` \[(\w+(?:-\w+)?)\] \(`([^`]+)`\)", re.MULTILINE)
# Raw line text follows the header
RAW_RE = re.compile(r"^\*\*raw:\*\* `([^`]+)`", re.MULTILINE)
# Folio header
HEADER_RE = re.compile(r"\*\*IVTFF header:\*\* `<![^>]+>`")
SECTION_RE = re.compile(r"\*\*Section:\*\* `(\w+)`")
L_RE = re.compile(r"\$L=([A-Z])")
H_RE = re.compile(r"\$H=(\d+)")

# Class-opener detection in raw IVTFF tokens
def opener_class(token: str) -> str:
    """Return the class-opener letter for a token; '?' if not parseable."""
    if not token:
        return "?"
    t = token.lstrip("[").lstrip("{")
    if t.startswith("@") or t.startswith("<"):
        return "?"
    if t.startswith(("oke", "okee")):
        return "oke"
    if t.startswith(("qok", "qot")):
        return "qok"
    if t.startswith("ok"):
        return "ok"
    if t.startswith("ot"):
        return "ot"
    if t.startswith("she"):
        return "she"
    if t.startswith("sh"):
        return "sh"
    if t.startswith("ch"):
        return "ch"
    if t.startswith("da"):
        return "da"
    if t.startswith(("aiin",)):
        return "aiin"
    if t and t[0].isalpha():
        return t[0]
    return "?"

# Tokenise a raw line into IVTFF tokens
def tokenise(raw: str) -> list:
    # Strip leading positional `<!HH:MM>` etc.
    raw = re.sub(r"^<[^>]+>", "", raw)
    # Strip `<%>` etc.
    raw = re.sub(r"<[^>]+>", "", raw)
    # Replace `[a:b]` brackets with the first option for class-opener detection
    raw_clean = re.sub(r"\[([a-z]+):[^\]]+\]", r"\1", raw)
    # Tokenise on . or , or whitespace
    tokens = re.split(r"[\.\,\s]+", raw_clean)
    return [t for t in tokens if t]

def score_line(raw: str, tier: str) -> dict:
    """Score a single line against author-fingerprints."""
    tokens = tokenise(raw)
    classes = [opener_class(t) for t in tokens]
    counts = Counter(classes)
    # I-keystone detection: capital `I` standalone or as a token starting with I
    i_keystone = sum(1 for t in tokens if t == "I" or t.startswith("I."))
    # f-class verb count (token starts with f and isn't followed by digits)
    f_count = counts.get("f", 0)
    p_count = counts.get("p", 0)
    o_count = counts.get("o", 0)
    d_count = counts.get("d", 0)
    r_count = counts.get("r", 0)
    s_count = counts.get("s", 0)
    y_count = counts.get("y", 0)
    c_count = counts.get("c", 0)
    qok = counts.get("qok", 0)
    oke = counts.get("oke", 0)
    ok_ = counts.get("ok", 0)
    ot_ = counts.get("ot", 0)
    sh_ = counts.get("sh", 0) + counts.get("she", 0)
    ch_ = counts.get("ch", 0)
    da_ = counts.get("da", 0)
    daiin = counts.get("aiin", 0)
    total = sum(counts.values())
    if total == 0:
        return None
    # Heuristic scores
    fontana_s = i_keystone * 5.0 + (1 if (f_count > 0 and o_count > 0 and r_count > 0 and d_count > 0) else 0) * 1.0
    despars_s = (f_count / total) * 4.0 + (1 if (f_count > 0 and i_keystone == 0) else 0) * 1.0
    albicus_s = (p_count / total) * 4.0 + min(oke / 2.0, 2.0) + (1 if (p_count > 0 and i_keystone == 0) else 0) * 1.0
    hartlieb_s = (p_count / total) * 2.5 + min(ot_ / 3.0, 2.0) + (1 if (oke > 0 and o_count > 0) else 0) * 1.0
    fusoris_arnaut_s = min(qok / 2.0, 2.5) + min(ch_ / 2.0, 2.0) + min(daiin / 3.0, 1.5)
    scores = {
        "Fontana": fontana_s,
        "Despars": despars_s,
        "Albicus": albicus_s,
        "Hartlieb": hartlieb_s,
        "Fusoris-Arnaut": fusoris_arnaut_s,
    }
    sorted_scores = sorted(scores.items(), key=lambda x: -x[1])
    top, top_score = sorted_scores[0]
    runner_score = sorted_scores[1][1] if len(sorted_scores) > 1 else 0
    margin = top_score - runner_score
    if top_score < 1.0:
        attribution = "UNRESOLVED"
    elif margin < 0.4:
        attribution = f"{top}/{sorted_scores[1][0]}"
    else:
        attribution = top
    return {
        "tier": tier,
        "tokens": total,
        "i_keystone": i_keystone,
        "f": f_count, "p": p_count, "o": o_count, "d": d_count, "r": r_count,
        "y": y_count, "s": s_count, "c": c_count,
        "qok": qok, "oke": oke, "ok": ok_, "ot": ot_, "sh": sh_, "ch": ch_, "daiin": daiin,
        "fontana_s": round(fontana_s, 2),
        "despars_s": round(despars_s, 2),
        "albicus_s": round(albicus_s, 2),
        "hartlieb_s": round(hartlieb_s, 2),
        "fusoris_s": round(fusoris_arnaut_s, 2),
        "attribution": attribution,
        "margin": round(margin, 2),
    }

def main() -> None:
    out_rows = []
    files = sorted(LATTICE_DIR.glob("f*.md"))
    for path in files:
        text = path.read_text(errors="replace")
        section_m = SECTION_RE.search(text)
        section = section_m.group(1) if section_m else "unknown"
        header_m = HEADER_RE.search(text)
        header = header_m.group(0) if header_m else ""
        l_m = L_RE.search(header) if header else None
        h_m = H_RE.search(header) if header else None
        currier = l_m.group(1) if l_m else ""
        hand = h_m.group(1) if h_m else ""
        # Find each line header + raw text
        # Iterate by alternating line header / raw matches
        line_headers = list(LINE_HEADER_RE.finditer(text))
        raws = list(RAW_RE.finditer(text))
        # Pair them by position (raw should follow header)
        for lh in line_headers:
            line_id = lh.group(1)
            line_type = lh.group(2)
            tier = lh.group(3)
            # Find the next raw after this header
            lh_end = lh.end()
            raw = None
            for r in raws:
                if r.start() > lh_end:
                    # ensure no other line header before this raw
                    interrupting = any(
                        oth.start() > lh_end and oth.start() < r.start()
                        for oth in line_headers if oth is not lh
                    )
                    if not interrupting:
                        raw = r.group(1)
                        break
            if raw is None:
                continue
            scored = score_line(raw, tier)
            if scored is None:
                continue
            scored.update({
                "folio": path.stem,
                "line_id": line_id,
                "line_type": line_type,
                "section": section,
                "currier": currier,
                "hand": hand,
            })
            out_rows.append(scored)
    # Output TSV
    cols = [
        "folio", "line_id", "line_type", "tier", "section", "currier", "hand",
        "attribution", "margin",
        "fontana_s", "despars_s", "albicus_s", "hartlieb_s", "fusoris_s",
        "tokens", "i_keystone",
        "f", "p", "o", "d", "r", "y", "s", "c",
        "qok", "oke", "ok", "ot", "sh", "ch", "daiin",
    ]
    OUT_TSV.write_text(
        "\t".join(cols) + "\n"
        + "\n".join("\t".join(str(r.get(c, "")) for c in cols) for r in out_rows)
        + "\n"
    )
    # Distribution
    print(f"Per-line scoring complete on {len(out_rows)} lines across {len(files)} folios.")
    print(f"Output: {OUT_TSV}")
    print("\n=== Attribution distribution (all lines) ===")
    counts = Counter(r["attribution"] for r in out_rows)
    for a, n in sorted(counts.items(), key=lambda x: -x[1]):
        pct = 100 * n / max(len(out_rows), 1)
        print(f"  {a:<35} {n:>6}  ({pct:.1f}%)")
    # I-keystone detection across all lines
    print("\n=== I-keystone hits (Fontana signature) ===")
    keystone = [r for r in out_rows if r["i_keystone"] > 0]
    for r in keystone:
        print(f"  {r['folio']}.{r['line_id']:<14} hand={r['hand']:<2} attribution={r['attribution']}")
    # Per-hand × Per-attribution
    print("\n=== Per-hand attribution distribution (counts) ===")
    hand_attrib = {}
    for r in out_rows:
        hand_attrib.setdefault(r["hand"] or "(none)", Counter())[r["attribution"]] += 1
    hands_seen = sorted(hand_attrib.keys())
    attribs = sorted(set(r["attribution"] for r in out_rows))
    print(f"\n{'Hand':<7}", end="")
    for a in attribs:
        print(f"{a[:14]:<16}", end="")
    print()
    for h in hands_seen:
        print(f"{h:<7}", end="")
        for a in attribs:
            n = hand_attrib[h].get(a, 0)
            print(f"{n:<16}", end="")
        print()

if __name__ == "__main__":
    main()
