#!/usr/bin/env python3
"""
K-CLASS POSITION-3 MINIM SIGNAL — RIGOROUS TEST
=================================================
Prior finding (minim_positional_by_gallows.py):
  k-class entries have minim-bearing tokens at position 3 in 35% of entries
  vs 6-10% for t/p and 0% for f.

Rigorous tests:
  1. Fisher's exact: k-class pos3 vs each other class at pos3
  2. Within k-class: is pos3 significantly elevated vs. mean background rate?
  3. Per-folio decomposition: which folios drive the signal?
  4. Token-level analysis: which EVA tokens appear at pos3 in k-class minim entries?
  5. Reclassify operator analysis: what Honeycutt Ai Labs operators do those tokens produce?
  6. Currier A/B split within k-class
  7. Contingency: k-class pos3 minim AND pos-0 minim — are they independent?
  8. Compare with [SH] peak at pos3 from sequence_slot_analysis
"""

import re, csv, sys, math
from collections import defaultdict, Counter
from itertools import combinations

sys.path.insert(0, '../../../resources/readers/provenance/source-5705c38194b8ecec.html')
from reclassify import reclassify_token

IVTFF = 'c7ffff9e1f3ecbec174e234c.txt'
CSV   = '../../../resources/readers/provenance/source-42f53525071b6eb1.html'
OUT   = '../../../resources/tools/provenance/index.html#s-039856f249f299a4'

MAX_POS = 20

COMPOUND_MAP = {'cth':'[CTH]','ckh':'[CKH]','cph':'[CPH]','cfh':'[CFH]'}
GALLOWS_SUPER = {'t':'t','[CTH]':'t','k':'k','[CKH]':'k',
                 'p':'p','[CPH]':'p','f':'f','[CFH]':'f'}

def first_op(tok):
    ops = reclassify_token(tok)
    if not ops: return 'X'
    op = ops[0]
    if op in ('[CTH]','[CKH]','[CPH]','[CFH]'): return op
    if op in 'tkpf': return op
    if op == '[CH]': return '[CH]'
    if op == '[SH]': return '[SH]'
    if op in ('[QO]',): return '[QO]'
    if op and op[0] in 'oaydeinrlsm': return op[0]
    return 'X'

def gallows_super(op):
    return GALLOWS_SUPER.get(op, None)

def has_minim(tok):
    ops = reclassify_token(tok)
    return any(op.startswith('[M') for op in ops)

def max_minim_run(tok):
    ops = reclassify_token(tok)
    m = 0
    for op in ops:
        if op.startswith('[M'):
            try: m = max(m, int(op[2:-1]))
            except: pass
    return m

def clean_tok(raw):
    raw = re.sub(r'\{c@\d+;(\w+)\}', r'\1', raw)
    raw = re.sub(r'\{(\w+)\}', r'\1', raw)
    raw = re.sub(r'\[([^:]+):[^\]]+\]', r'\1', raw)
    raw = re.sub(r'<%>|<[^>]+>', '', raw)
    return re.sub(r'[^a-zA-Z]', '', raw).lower()

def tokenize(text):
    text = re.sub(r'@\d+;', ' ', text)
    text = re.sub(r'<[^>]+>', ' ', text)
    toks = [clean_tok(t) for t in re.split(r'[.,\s]+', text)]
    return [t for t in toks if t]

# ── Load metadata ────────────────────────────────────────────────────────────
folio_section = {}
folio_currier = {}
with open(CSV) as fh:
    for row in csv.DictReader(fh):
        folio_section[row['folio_id']] = row['section']
        folio_currier[row['folio_id']] = row['currier_language']

herbal_folios = {f for f, s in folio_section.items()
                 if s in ('herbal_A', 'herbal_B')}

# ── Parse IVTFF ──────────────────────────────────────────────────────────────
line_re = re.compile(r'^<(f[\w.]+),([^>]+)>\s*(.*)')

# Each entry: (folio, currier, initial_op, gc, [tok_list])
all_entries = []

current_folio = None
current_toks  = []

def flush(folio, toks):
    if not folio or not toks: return
    base = re.sub(r'\.\d+$', '', folio)
    if base not in herbal_folios: return
    first = first_op(toks[0]) if toks else 'X'
    gc = gallows_super(first)
    if gc is None: gc = 'other'
    cur = folio_currier.get(base, '?')
    all_entries.append({
        'folio':   base,
        'currier': cur,
        'init_op': first,
        'gc':      gc,
        'toks':    toks[:],
    })

with open(IVTFF, encoding='utf-8', errors='replace') as fh:
    for line in fh:
        m = line_re.match(line.rstrip())
        if not m: continue
        fid, marker, text = m.group(1), m.group(2), m.group(3)
        base = re.sub(r'\.\d+$', '', fid)
        if base not in herbal_folios: continue
        toks = tokenize(text)
        if not toks: continue
        if '@P' in marker:
            flush(current_folio, current_toks)
            current_folio = base
            current_toks  = toks[:]
        elif '+P' in marker and base == current_folio:
            current_toks.extend(toks)

flush(current_folio, current_toks)

lines = []
def w(s=''): lines.append(str(s))

w("K-CLASS POSITION-3 MINIM SIGNAL — RIGOROUS TEST")
w("=" * 70)
w(f"Total herbal entries: {len(all_entries)}")
gc_cnt = Counter(e['gc'] for e in all_entries)
for gc, n in sorted(gc_cnt.items(), key=lambda x: -x[1]):
    w(f"  {gc}: n={n}")
w()

# ── BUILD: per-class per-position minim counts ───────────────────────────────
# pos_data[gc][k] = {'minim': count, 'total': count}
pos_data = {gc: [{'minim': 0, 'total': 0} for _ in range(MAX_POS)]
            for gc in 'tkpf'}

# Also store per-entry data for detailed analysis
entry_pos3 = []  # list of dicts for each entry at pos 3

for e in all_entries:
    gc = e['gc']
    if gc not in 'tkpf': continue
    toks = e['toks']
    for k in range(min(len(toks), MAX_POS)):
        pos_data[gc][k]['total'] += 1
        if has_minim(toks[k]):
            pos_data[gc][k]['minim'] += 1
            if k == 3:
                entry_pos3.append({
                    'folio':   e['folio'],
                    'currier': e['currier'],
                    'gc':      gc,
                    'tok':     toks[k],
                    'tok_ops': reclassify_token(toks[k]),
                    'context': toks[max(0,k-2):k+4],
                })

# ── PART 1: Fisher's exact tests ─────────────────────────────────────────────
w("PART 1: FISHER'S EXACT TEST — k-class pos3 vs. other classes")
w("-" * 70)
w("H₀: minim rate at position 3 is the same for k-class as for comparison class")
w()

def hypergeometric_p(a, b, c, d):
    """
    2×2 table: [[a,b],[c,d]]  a=k_minim, b=k_no, c=comp_minim, d=comp_no
    One-tailed p: P(X >= a) under hypergeometric(N=a+b+c+d, K=a+c, n=a+b)
    """
    N = a + b + c + d
    K = a + c     # total minim
    n = a + b     # k-class total
    # P(X=x) = C(K,x)*C(N-K,n-x)/C(N,n)
    def log_comb(n, k):
        if k < 0 or k > n: return -math.inf
        return sum(math.log(n - i) - math.log(i + 1) for i in range(k))
    log_cn = log_comb(N, n)
    p_ge_a = 0.0
    for x in range(a, min(K, n) + 1):
        lp = log_comb(K, x) + log_comb(N - K, n - x) - log_cn
        p_ge_a += math.exp(lp)
    return min(p_ge_a, 1.0)

k_pos3 = pos_data['k'][3]
k_a = k_pos3['minim']   # k-class minim at pos3
k_b = k_pos3['total'] - k_a  # k-class no-minim at pos3

w(f"  k-class pos3: {k_a}/{k_pos3['total']} = {k_a/k_pos3['total']:.3f}")
w()

for comp_gc in 'tpf':
    comp = pos_data[comp_gc][3]
    c = comp['minim']
    d = comp['total'] - c
    if comp['total'] == 0: continue
    p = hypergeometric_p(k_a, k_b, c, d)
    or_val = (k_a * d) / max(k_b * c, 0.001)
    w(f"  k vs {comp_gc}: k={k_a}/{k_b+k_a}, {comp_gc}={c}/{c+d}  "
      f"OR={or_val:.2f}  p(one-tail)={p:.4f}  "
      f"{'*SIG*' if p < 0.05 else 'ns'}")
w()

# ── PART 2: Within k-class — is pos3 elevated vs. background? ────────────────
w("PART 2: WITHIN K-CLASS — IS POS3 ELEVATED VS. BACKGROUND RATE?")
w("-" * 70)
w("Background = mean minim rate across all positions 1-19 (excluding pos0, pos3)")
w()

k_data = pos_data['k']
k_n_entries = gc_cnt.get('k', 0)

# Background: positions 1,2,4-19 (exclude pos0=gallows, pos3=signal)
bg_positions = [k for k in range(1, MAX_POS) if k != 3]
bg_total_minim = sum(k_data[k]['minim'] for k in bg_positions)
bg_total_n     = sum(k_data[k]['total'] for k in bg_positions)
bg_rate        = bg_total_minim / max(bg_total_n, 1)

pos3_minim = k_data[3]['minim']
pos3_total = k_data[3]['total']
pos3_rate  = pos3_minim / max(pos3_total, 1)

w(f"  k-class pos3: {pos3_minim}/{pos3_total} = {pos3_rate:.4f}")
w(f"  k-class background (pos1-2,4-19): {bg_total_minim}/{bg_total_n} = {bg_rate:.4f}")
w(f"  Fold above background: {pos3_rate/max(bg_rate,0.001):.2f}x")
w()

# Fisher's exact: pos3 vs background pool
p_bg = hypergeometric_p(pos3_minim,
                         pos3_total - pos3_minim,
                         bg_total_minim,
                         bg_total_n - bg_total_minim)
w(f"  Fisher's exact (pos3 vs background): p={p_bg:.4f}  "
  f"{'*SIG*' if p_bg < 0.05 else 'ns'}")
w()

# Full positional profile for k-class
w("  k-class positional minim profile:")
w(f"  {'pos':>4}  {'minim':>6}  {'total':>6}  {'rate':>6}  marker")
w(f"  {'---':>4}  {'-----':>6}  {'-----':>6}  {'----':>6}  ------")
for k in range(MAX_POS):
    if k_data[k]['total'] == 0: break
    rate = k_data[k]['minim'] / k_data[k]['total']
    bar  = '█' * int(rate * 30)
    mark = ' ← SIGNAL' if k == 3 else ''
    w(f"  {k:>4}  {k_data[k]['minim']:>6}  {k_data[k]['total']:>6}  {rate:>6.3f}  {bar}{mark}")
w()

# ── PART 3: Per-folio decomposition ──────────────────────────────────────────
w("PART 3: PER-FOLIO DECOMPOSITION — which folios drive the k-class pos3 signal?")
w("-" * 70)

k_entries = [e for e in all_entries if e['gc'] == 'k']
folio_pos3 = defaultdict(lambda: {'minim': 0, 'total': 0})

for e in k_entries:
    toks = e['toks']
    if len(toks) > 3:
        folio_pos3[e['folio']]['total'] += 1
        if has_minim(toks[3]):
            folio_pos3[e['folio']]['minim'] += 1

w(f"  {'folio':<10}  {'section':<12}  {'currier':<4}  {'pos3_minim':>10}  {'pos3_total':>10}  {'rate':>6}  tok_at_pos3")
w(f"  {'-----':<10}  {'-------':<12}  {'-------':<4}  {'----------':>10}  {'----------':>10}  {'----':>6}  ----------")

for folio in sorted(folio_pos3.keys()):
    d    = folio_pos3[folio]
    rate = d['minim'] / max(d['total'], 1)
    sec  = folio_section.get(folio, '?')
    cur  = folio_currier.get(folio, '?')
    # Collect pos3 tokens for this folio
    pos3_toks = [e['toks'][3] for e in k_entries
                 if e['folio'] == folio and len(e['toks']) > 3]
    tok_str = ', '.join(Counter(pos3_toks).most_common(3)[i][0]
                        if i < len(Counter(pos3_toks)) else ''
                        for i in range(min(3, len(Counter(pos3_toks)))))
    w(f"  {folio:<10}  {sec:<12}  {cur:<4}  {d['minim']:>10}  {d['total']:>10}  {rate:>6.3f}  {tok_str}")
w()

# ── PART 4: Token-level analysis at pos3 ─────────────────────────────────────
w("PART 4: TOKEN-LEVEL ANALYSIS — what tokens appear at pos3 in k-class minim entries?")
w("-" * 70)

w("  Minim-bearing tokens at position 3 in k-class entries:")
w(f"  {'token':<15}  {'count':>5}  {'operators':<40}  folios")
w(f"  {'-----':<15}  {'-----':>5}  {'--------':<40}  ------")
tok_counter = Counter(e['tok'] for e in entry_pos3 if e['gc'] == 'k')
for tok, cnt in tok_counter.most_common():
    ops   = reclassify_token(tok)
    ops_s = ' '.join(ops)
    folios = ', '.join(sorted({e['folio'] for e in entry_pos3
                               if e['gc'] == 'k' and e['tok'] == tok}))
    w(f"  {tok:<15}  {cnt:>5}  {ops_s:<40}  {folios}")
w()

# Compare with pos3 tokens in non-k classes
w("  For comparison — pos3 MINIM tokens in other classes:")
for comp_gc in 'tpf':
    toks = Counter(e['tok'] for e in entry_pos3 if e['gc'] == comp_gc)
    if toks:
        tok_str = ', '.join(f"{t}({c})" for t, c in toks.most_common(5))
        w(f"  {comp_gc}-class: {tok_str}")
    else:
        w(f"  {comp_gc}-class: none")
w()

# ── PART 5: Context window at pos3 ───────────────────────────────────────────
w("PART 5: CONTEXT WINDOW — full pos1..pos5 sequence for k-class pos3 minim entries")
w("-" * 70)

w(f"  {'folio':<10}  {'cur':<3}  {'pos1':>8}  {'pos2':>8}  {'pos3(minim)':>12}  {'pos4':>8}  {'pos5':>8}")
w(f"  {'-----':<10}  {'---':<3}  {'----':>8}  {'----':>8}  {'-----------':>12}  {'----':>8}  {'----':>8}")

for e in entry_pos3:
    if e['gc'] != 'k': continue
    toks = [e['folio'].split('-')[0]] + e['context']
    ctx = e['context']  # toks[max(0,3-2):3+4] = positions 1..6 (relative)
    # Since context is toks[1..6], pos3 is at index 2 of context
    def safe(lst, i):
        return lst[i] if 0 <= i < len(lst) else ''
    # context = toks[pos1..pos6]
    full_toks = [e['folio']]  # pad folio
    # Actually need to get positions 1-5 from the original entry
    orig = next((x for x in k_entries
                 if x['folio'] == e['folio'] and
                 len(x['toks']) > 3 and x['toks'][3] == e['tok']), None)
    if orig:
        row_toks = orig['toks']
        p = lambda k: row_toks[k] if k < len(row_toks) else ''
        ops3 = '/'.join(reclassify_token(p(3)))
        w(f"  {e['folio']:<10}  {e['currier']:<3}  "
          f"{p(1):>8}  {p(2):>8}  {p(3):>12}  {p(4):>8}  {p(5):>8}  ← {ops3}")
w()

# ── PART 6: Currier split within k-class ─────────────────────────────────────
w("PART 6: CURRIER SPLIT WITHIN K-CLASS")
w("-" * 70)

for cur in ('A', 'B'):
    k_cur = [e for e in k_entries if e['currier'] == cur]
    if not k_cur: continue
    pos3_m = sum(1 for e in k_cur if len(e['toks']) > 3 and has_minim(e['toks'][3]))
    pos3_t = sum(1 for e in k_cur if len(e['toks']) > 3)
    rate   = pos3_m / max(pos3_t, 1)
    w(f"  Currier {cur} (n={len(k_cur)}): pos3 minim {pos3_m}/{pos3_t} = {rate:.3f}")
w()

# ── PART 7: Compare k-class pos3 with [SH] peak at pos3 ──────────────────────
w("PART 7: CROSS-COMPARISON WITH [SH] PEAK AT POSITION 3 (from sequence analysis)")
w("-" * 70)
w("Prior finding: [SH] peaks at position 3 in herbal A (chi-sq p=0.0048)")
w("Question: is the k-class pos3 minim signal the SAME entries as the [SH] peak,")
w("or are they independent structural features?")
w()

# For each k-class entry, record: (has_SH_at_pos3, has_minim_at_pos3)
sh_minim_table = {'sh_and_minim': 0, 'sh_only': 0, 'minim_only': 0, 'neither': 0}

for e in k_entries:
    toks = e['toks']
    if len(toks) <= 3: continue
    tok3 = toks[3]
    ops3 = reclassify_token(tok3)
    has_sh = '[SH]' in ops3 or tok3.startswith('sh')
    hm     = has_minim(tok3)
    if has_sh and hm:   sh_minim_table['sh_and_minim'] += 1
    elif has_sh:        sh_minim_table['sh_only'] += 1
    elif hm:            sh_minim_table['minim_only'] += 1
    else:               sh_minim_table['neither'] += 1

w("  k-class pos3 token classification:")
for cat, cnt in sh_minim_table.items():
    w(f"    {cat:<20}: {cnt}")
w()
w("  Same analysis for herbal A across ALL gallows classes:")
hA_entries = [e for e in all_entries if folio_section.get(e['folio']) == 'herbal_A'
              and e['gc'] in 'tkpf' and len(e['toks']) > 3]
sh_m_all = Counter()
for e in hA_entries:
    tok3 = e['toks'][3]
    ops3 = reclassify_token(tok3)
    has_sh = tok3.startswith('sh')
    hm     = has_minim(tok3)
    key = f"{e['gc']}|sh={'Y' if has_sh else 'N'}|m={'Y' if hm else 'N'}"
    sh_m_all[key] += 1
for key, cnt in sorted(sh_m_all.items()):
    w(f"    {key}: {cnt}")
w()

# ── PART 8: Grand summary ─────────────────────────────────────────────────────
w("PART 8: GRAND SUMMARY")
w("=" * 70)
w()

# Compute the overall signal strength
k_p3_rate = pos_data['k'][3]['minim'] / max(pos_data['k'][3]['total'], 1)
k_bg_rate  = bg_rate
fold       = k_p3_rate / max(k_bg_rate, 0.001)

w(f"k-class position-3 signal:")
w(f"  Rate at pos3:    {k_p3_rate:.3f}  ({pos_data['k'][3]['minim']}/{pos_data['k'][3]['total']} entries)")
w(f"  Background rate: {k_bg_rate:.3f}")
w(f"  Fold above bg:   {fold:.2f}x")
w(f"  Fisher vs bg:    p={p_bg:.4f}")
w()
w("Fisher vs other classes at pos3:")
for comp_gc in 'tpf':
    comp = pos_data[comp_gc][3]
    c = comp['minim']; d = comp['total'] - c
    p = hypergeometric_p(k_a, k_b, c, d)
    w(f"  k vs {comp_gc}: p={p:.4f}  {'*SIG*' if p < 0.05 else 'ns'}")
w()
w("Interpretation:")
w("  If pos3 Fisher p < 0.05 vs background AND vs other classes:")
w("    → k-class entries have a specific structural token at position 3")
w("    → Combined with [SH] pos3 peak (herbal A) and D-slot hypothesis:")
w("      position 3 = H-slot sub-qualifier (herb-class modifier)")
w("      k-class specific = k-gallows entries use a specific qualifier here")
w("    → This is gallows-conditional slot grammar: the H-slot position")
w("      shifts or is marked differently depending on which gallows opened the entry")
w()
w("  If null:")
w("    → The k-class pos3 observation is sampling noise from n=20")

with open(OUT, 'w') as fh:
    fh.write('\n'.join(lines))

print(f"Written: {OUT}")
print(f"Total k-class entries: {sum(1 for e in all_entries if e['gc']=='k')}")
