"""Independent recompute for the cloud-phi phase1 identity-negation paper.
Usage: python3 -I analyze.py /home/vesper/data/cloudphi/repo
Stdlib only (math.comb). Reads FINAL_ADJUDICATED_CODES.md and sealed_key.jsonl as DATA.
Does NOT import or execute the authors' script.
"""
import sys, json, re
from math import comb, exp, lgamma, log
from collections import Counter, defaultdict
from pathlib import Path

root = Path(sys.argv[1])
codes_txt = (root / "recompute/FINAL_ADJUDICATED_CODES.md").read_text(encoding="utf-8")
key_txt = (root / "recompute/sealed_key.jsonl").read_text(encoding="utf-8")

# ---------- parse (my own regex: every 'Mnnn|code' cell, tolerant of ** bold) ----------
cells = re.findall(r"\|\s*(M\d{3})\s*\|\s*\**\s*(FA|PD|SC|M|D)\s*\**\s*(?=\|)", codes_txt)
codes = {}
for i, c in cells:
    assert i not in codes, i
    codes[i] = c
print("parsed codes:", len(codes))
assert len(codes) == 96

rows = []
for ln in key_txt.splitlines():
    if not ln.strip():
        continue
    d = json.loads(ln)
    cond = d["condition"].replace("condition_", "")
    fetch = cond.endswith("_fetch")
    cond = cond.replace("_fetch", "")
    cond = {"a": "A", "bprime": "B", "c1m": "C1", "c2": "C2"}[cond]
    t = d["trial"]
    m = re.fullmatch(r"trial_(\d+)_r(\d+)", t)
    tm, rp = (int(m.group(1)), int(m.group(2))) if m else (None, None)
    arm = 1 if d["arm"].endswith("arm1") else 2
    assert arm == (2 if fetch else 1) or cond == "C2" and arm == 1, (d,)
    rows.append(dict(item=d["item_id"], cond=cond, arm=arm, tmpl=tm, rep=rp, trial=t, code=codes[d["item_id"]]))
print("key rows:", len(rows), "baselines:", [r["trial"] for r in rows if r["tmpl"] is None])
print("baseline rows:", [(r["item"], r["cond"], r["arm"], r["trial"]) for r in rows if r["tmpl"] is None])

# ---------- stats helpers ----------
def lchoose(n, k): return lgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1)
def hyp(k, n1, K, N): return exp(lchoose(K, k) + lchoose(N - K, n1 - k) - lchoose(N, n1))
def fisher2(a, n1, b, n2):
    K, N = a + b, n1 + n2
    po = hyp(a, n1, K, N)
    return sum(hyp(k, n1, K, N) for k in range(max(0, K - n2), min(K, n1) + 1) if hyp(k, n1, K, N) <= po * (1 + 1e-9))
def fisher_less(a, n1, b, n2):  # P(X<=a) : group 1 has fewer events
    K, N = a + b, n1 + n2
    return sum(hyp(k, n1, K, N) for k in range(max(0, K - n2), a + 1))
def chi2_p(a, n1, b, n2, yates=False):
    N = n1 + n2; K = a + b
    tab = [[a, n1 - a], [b, n2 - b]]
    e = [[n1 * K / N, n1 * (N - K) / N], [n2 * K / N, n2 * (N - K) / N]]
    s = 0
    for i in range(2):
        for j in range(2):
            dlt = abs(tab[i][j] - e[i][j])
            if yates: dlt = max(0, dlt - 0.5)
            s += dlt ** 2 / e[i][j]
    from math import erfc, sqrt
    return s, erfc(sqrt(s / 2))  # chi2 df=1 sf = erfc(sqrt(x/2))
def binom_pmf(k, n, p): return comb(n, k) * p ** k * (1 - p) ** (n - k)
def sign2(w, l):
    n = w + l; k = min(w, l)
    return min(1.0, 2 * sum(comb(n, i) for i in range(k + 1)) / 2 ** n)
def cp(k, n, alpha=0.05):  # Clopper-Pearson by bisection
    def cdf(x, nn, p): return sum(binom_pmf(i, nn, p) for i in range(x + 1))
    lo = 0.0
    if k > 0:
        a, b = 0.0, 1.0
        for _ in range(100):
            m = (a + b) / 2
            if 1 - cdf(k - 1, n, m) < alpha / 2: a = m
            else: b = m
        lo = (a + b) / 2
    hi = 1.0
    if k < n:
        a, b = 0.0, 1.0
        for _ in range(100):
            m = (a + b) / 2
            if cdf(k, n, m) > alpha / 2: a = m
            else: b = m
        hi = (a + b) / 2
    return lo, hi

COLL = {"D", "SC"}
tr = [r for r in rows if r["tmpl"] is not None]
def S(rs=rows, **kw): return [r for r in rs if all(r[k] == v for k, v in kw.items())]
def coll(rs): return sum(r["code"] in COLL for r in rs)
def fa(rs): return sum(r["code"] == "FA" for r in rs)

print("\n=== CODE DISTRIBUTION BY CONDITION (all 96) ===")
for c in ["A", "B", "C1", "C2"]:
    rs = S(cond=c)
    print(c, len(rs), dict(Counter(r["code"] for r in rs)))
print("overall", dict(Counter(r["code"] for r in rows)))

print("\n=== CHECK 2: the two headline numbers (collapse+disavowal = D+SC) ===")
B, C1, C2, A = S(cond="B"), S(cond="C1"), S(cond="C2"), S(cond="A")
print("registered (96 items): A %d/%d  B' %d/%d  C1m %d/%d  C2 %d/%d  pooled %d/96" % (coll(A), len(A), coll(B), len(B), coll(C1), len(C1), coll(C2), len(C2), coll(rows)))
Bt, C1t, C2t, At = S(tr, cond="B"), S(tr, cond="C1"), S(tr, cond="C2"), S(tr, cond="A")
print("trials only (90): A %d/%d B' %d/%d C1m %d/%d C2 %d/%d" % (coll(At), len(At), coll(Bt), len(Bt), coll(C1t), len(C1t), coll(C2t), len(C2t)))
print("B' collapse items:", [(r["item"], r["code"], r["arm"], r["tmpl"]) for r in B if r["code"] in COLL])
print("C1m collapse items:", [(r["item"], r["code"], r["arm"], r["tmpl"]) for r in C1 if r["code"] in COLL])
print("C2 collapse items:", [(r["item"], r["code"], r["arm"], r["tmpl"]) for r in C2 if r["code"] in COLL])
print("baselines collapsed?", [(r["item"], r["cond"], r["code"]) for r in rows if r["tmpl"] is None])
def report(label, a, n1, b, n2):
    s0, p0 = chi2_p(a, n1, b, n2); s1, p1 = chi2_p(a, n1, b, n2, True)
    print("%-34s %d/%d vs %d/%d  Fisher2=%.4f  Fisher1(less)=%.4f  chi2=%.3f p=%.4f  chi2Yates=%.3f p=%.4f" % (label, a, n1, b, n2, fisher2(a, n1, b, n2), fisher_less(a, n1, b, n2), s0, p0, s1, p1))
report("B' vs C1m registered", 2, 32, 6, 32)
report("B' vs C1m trials-only", 2, 30, 6, 30)
report("B' vs C2 registered", 2, 32, 4, 21)
report("B' vs pooled controls (reg)", 2, 32, 10, 53)
report("B' vs pooled controls (trials)", 2, 30, 10, 50)
report("B' vs C1m+C2+A?? (reg, incl A)", 2, 32, 10, 64)
report("Vesper guess 3/48 vs 9/48", 3, 48, 9, 48)
# Arm cut
for c in ["B", "C1", "C2"]:
    for arm in (1, 2):
        rs = S(tr, cond=c, arm=arm)
        if rs: print("  trials %s arm%d: %d/%d" % (c, arm, coll(rs), len(rs)))
ctrl1 = [r for r in tr if r["cond"] in ("C1", "C2") and r["arm"] == 1]
report("Arm1 B' vs C1m+C2", 0, 20, coll(ctrl1), len(ctrl1))
report("Arm1 B' vs C1m", 0, 20, 3, 20)
report("Arm1 B' vs C2", 0, 20, 4, 20)
report("Arm2 B' vs C1m", 2, 10, 3, 10)
print("CP95 B' 2/32 %s ; C1m 6/32 %s" % (tuple(round(x, 3) for x in cp(2, 32)), tuple(round(x, 3) for x in cp(6, 32))))
print("CP95 B' 0/20 %s ; B' 0/30? ; 0/32 %s" % (tuple(round(x, 3) for x in cp(0, 20)), tuple(round(x, 3) for x in cp(0, 32))))
# difference CI (Newcombe-ish via Wald, just for report)
from math import sqrt
p1, p2 = 2 / 32, 6 / 32
se = sqrt(p1 * (1 - p1) / 32 + p2 * (1 - p2) / 32)
print("diff C1m-B' = %.3f, Wald95 = (%.3f, %.3f)" % (p2 - p1, p2 - p1 - 1.96 * se, p2 - p1 + 1.96 * se))

# power of the registered contrast
def power(p1, p2, n1, n2, alpha=0.05):
    pw = 0.0
    for a in range(n1 + 1):
        pa = binom_pmf(a, n1, p1)
        if pa < 1e-12: continue
        for b in range(n2 + 1):
            pb = binom_pmf(b, n2, p2)
            if pb < 1e-12: continue
            if fisher2(a, n1, b, n2) <= alpha: pw += pa * pb
    return pw
print("POWER (Fisher 2-sided .05) at true 6.2 pct vs 18.8 pct, n=32/32: %.3f" % power(2 / 32, 6 / 32, 32, 32))
print("POWER at true 6.7 pct vs 20 pct, n=30/30: %.3f ; n=62/62: %.3f" % (power(.067, .2, 30, 30), power(.067, .2, 62, 62)))

print("\n=== CHECK 1: could kill rules fire? (bridge prediction section 3) ===")
# Falsifier 1: B' collapse >= C1m collapse, n=30 each.
def p_cmp(p1, p2, n=30):
    lt = eq = gt = 0.0
    for a in range(n + 1):
        for b in range(n + 1):
            pr = binom_pmf(a, n, p1) * binom_pmf(b, n, p2)
            if a < b: lt += pr
            elif a == b: eq += pr
            else: gt += pr
    return lt, eq, gt
for lab, (p1_, p2_) in {"H1 point (6.7% vs 20%)": (2 / 30, 6 / 30), "H1 Phase1 reg (6.25% vs 18.75%)": (2 / 32, 6 / 32), "null both 12.5%": (.125, .125), "null both 6.7%": (.067, .067), "null both 20%": (.2, .2), "reversed (20% vs 6.7%)": (.2, 2 / 30)}.items():
    lt, eq, gt = p_cmp(p1_, p2_)
    print("%-34s P(B'<C1m)=%.3f  P(tie)=%.3f  P(B'>C1m)=%.3f  -> P(kill fires = B'>=C1m)=%.3f" % (lab, lt, eq, gt, eq + gt))
# the falsifier has no magnitude: smallest outcome that passes P3 vs smallest that is significant
print("P3 passes at 5/30 vs 6/30? Fisher2 p=%.3f" % fisher2(5, 30, 6, 30))
print("P3 passes at 0/30 vs 1/30? Fisher2 p=%.3f" % fisher2(0, 30, 1, 30))
# smallest C1m count c such that B' b gives Fisher2 <=.05 at n=30
for b in range(0, 6):
    for c in range(b, 31):
        if fisher2(b, 30, c, 30) <= 0.05:
            print("  n=30/30: B'=%d needs C1m>=%d for p<=.05 (two-sided)" % (b, c)); break
for b in range(0, 6):
    for c in range(b, 63):
        if fisher2(b, 62, c, 62) <= 0.05:
            print("  n=62/62: B'=%d needs C1m>=%d for p<=.05 (two-sided)" % (b, c)); break
for b in range(0, 6):
    for c in range(b, 33):
        if fisher2(b, 32, c, 32) <= 0.05:
            print("  n=32/32: B'=%d needs C1m>=%d for p<=.05 (two-sided)" % (b, c)); break
# Falsifier 2: PNR = 0 in 30 B' trials
for p in (4 / 32, 4 / 30, 0.05, 0.02):
    print("P(PNR=0 of 30 | rate %.3f) = %.4f" % (p, (1 - p) ** 30))
print("CP95 of 4/32 PNR: ", tuple(round(x, 3) for x in cp(4, 32)))
# Falsifier 3: residue-free in B' > 3/30
print("B' residue-free Phase1 0/32; CP upper 95%% = %.3f; P(>3/30 | p=upper)=%.3f ; P(>3/30 | p=0.03)=%.4f ; P(>3/30|p=0.05)=%.3f" % (
    cp(0, 32)[1], sum(binom_pmf(k, 30, cp(0, 32)[1]) for k in range(4, 31)),
    sum(binom_pmf(k, 30, .03) for k in range(4, 31)), sum(binom_pmf(k, 30, .05) for k in range(4, 31))))
# Prediction P1 interval: 0-5 for p=2/30
print("P1 interval 0-5 coverage at p=.067: %.3f ; P2 interval 2-10 at p=.2: %.3f ; P4 PNR 1-8 at p=.133: %.3f ; P5 C1m 5-15 at p=11/32: %.3f" % (
    sum(binom_pmf(k, 30, 2 / 30) for k in range(0, 6)), sum(binom_pmf(k, 30, .2) for k in range(2, 11)), sum(binom_pmf(k, 30, 4 / 30) for k in range(1, 9)), sum(binom_pmf(k, 30, 11 / 32) for k in range(5, 16))))

print("\n=== CHECK 3: mere repeat of old rates at doubled n ===")
report("pooled B' 4/62 vs C1m 12/62", 4, 62, 12, 62)
report("pooled trials 4/60 vs 12/60", 4, 60, 12, 60)
report("pooled B' 4/64? (52 vs 52 wording): scaled 3/52 vs 10/52", 3, 52, 10, 52)
report("bridge alone, exact old rates 2/30 v 6/30", 2, 30, 6, 30)
# P(pooled test significant) under H1 rates for bridge; given Phase1 fixed 2/30 vs 6/30 (trials) add bridge
def p_pool_sig(p1, p2, base=(2, 30, 6, 30), n=30, alpha=0.05):
    pw = 0.0
    for a in range(n + 1):
        pa = binom_pmf(a, n, p1)
        for b in range(n + 1):
            pr = pa * binom_pmf(b, n, p2)
            if pr < 1e-12: continue
            if fisher2(base[0] + a, base[1] + n, base[2] + b, base[3] + n) <= alpha: pw += pr
    return pw
print("P(pooled 60 vs 60 Fisher2<=.05 | bridge at 6.7%% vs 20%%)=%.3f ; | bridge null 12.5%% both = %.3f ; | bridge reversed = %.3f" % (
    p_pool_sig(2 / 30, 6 / 30), p_pool_sig(.125, .125), p_pool_sig(.2, 2 / 30)))
print("P(bridge alone sig | H1 6.7 vs 20)= %.3f" % power(2 / 30, 6 / 30, 30, 30))

print("\n=== FULL-ASSERT (unregistered reanalysis) ===")
print("FA B' %d/30  C1m %d/30  C2 %d/20  A %d/10" % (fa(Bt), fa(C1t), fa(C2t), fa(At)))
print("FA Fisher2 B' vs C1m 23/30 vs 6/30: %.2e" % fisher2(23, 30, 6, 30))
w = l = t = 0; perT = []
for T in range(1, 11):
    fb = fa([r for r in Bt if r["tmpl"] == T]); fc = fa([r for r in C1t if r["tmpl"] == T])
    perT.append((T, fb, fc))
    if fb > fc: w += 1
    elif fb < fc: l += 1
    else: t += 1
print("per-template FA (T, B', C1m, of 3 reps each):", perT)
print("sign test wins/losses/ties = %d/%d/%d  two-sided p=%.4f ; ties as half-win? one-sided with 10 incl ties as losses: %.4f" % (w, l, t, sign2(w, l), sum(comb(10, i) for i in range(8, 11)) / 2 ** 10))
# FA by arm
for c in ("B", "C1"):
    for arm in (1, 2):
        rs = S(tr, cond=c, arm=arm); print("  FA %s arm%d: %d/%d" % (c, arm, fa(rs), len(rs)))
# paired-by-template difference sum, permutation across reps? Wilcoxon-ish: exact permutation of condition labels within template (rep-level)
import itertools, random
# exact within-template permutation of condition labels: stat = total FA diff
def perm_p():
    obs = fa(Bt) - fa(C1t)
    # each template: 6 trials, 3 B' 3 C1m, k total FA among 6; diff distribution hypergeometric
    dists = []
    for T in range(1, 11):
        fb = fa([r for r in Bt if r["tmpl"] == T]); fc = fa([r for r in C1t if r["tmpl"] == T]); K = fb + fc
        d = defaultdict(float)
        for x in range(max(0, K - 3), min(3, K) + 1):
            d[x - (K - x)] += hyp(x, 3, K, 6)
        dists.append(d)
    tot = {0: 1.0}
    for d in dists:
        nt = defaultdict(float)
        for a, pa in tot.items():
            for b, pb in d.items(): nt[a + b] += pa * pb
        tot = nt
    return sum(p for v, p in tot.items() if abs(v) >= abs(obs) - 1e-9), obs
print("within-template permutation (stratified exact) p, obs diff = ", perm_p())
# FA with C2 and baselines? FA of C2
print("FA 'hold' (M+FA) B' %d/30 C1m %d/30" % (fa(Bt) + sum(r['code']=='M' for r in Bt), fa(C1t) + sum(r['code']=='M' for r in C1t)))
# tiers (post-hoc map from authors' reanalysis; not in repo, taken from their script)
TIER = {1: "NEUTRAL", 2: "NEUTRAL", 5: "NEUTRAL", 6: "NEUTRAL", 10: "NEUTRAL", 3: "SHARED", 9: "SHARED", 4: "B-ONLY", 7: "MIXED", 8: "MIXED"}
def tierfa(tset):
    b = [r for r in Bt if TIER[r["tmpl"]] in tset]; c = [r for r in C1t if TIER[r["tmpl"]] in tset]
    return fa(b), len(b), fa(c), len(c)
for lab, ts in [("NEUTRAL", {"NEUTRAL"}), ("NEUTRAL+SHARED", {"NEUTRAL", "SHARED"}), ("B-ONLY+MIXED", {"B-ONLY", "MIXED"})]:
    a_, n1, b_, n2 = tierfa(ts)
    print("FA tier %-16s B' %d/%d vs C1m %d/%d  Fisher2=%.4f" % (lab, a_, n1, b_, n2, fisher2(a_, n1, b_, n2)))
b_, c_ = [r for r in Bt if TIER[r["tmpl"]] == "NEUTRAL"], [r for r in C1t if TIER[r["tmpl"]] == "NEUTRAL"]
print("NEUTRAL collapse B' %d/15 vs C1m %d/15 Fisher2=%.3f" % (coll(b_), coll(c_), fisher2(coll(b_), 15, coll(c_), 15)))
# FA restricted to NEUTRAL templates, sign test over 5 templates
w = l = 0
for T in (1, 2, 5, 6, 10):
    fb = fa([r for r in Bt if r["tmpl"] == T]); fc = fa([r for r in C1t if r["tmpl"] == T])
    print("  NEUTRAL T%d FA B' %d C1m %d" % (T, fb, fc))
# Is FA gap in config-referencing vs role-replacement?
RR = {1, 5, 8, 9}
for lab, ts in (("RR", RR), ("CR", set(range(1, 11)) - RR)):
    b = [r for r in Bt if r["tmpl"] in ts]; c = [r for r in C1t if r["tmpl"] in ts]
    print("FA %s B' %d/%d C1m %d/%d Fisher2=%.4g" % (lab, fa(b), len(b), fa(c), len(c), fisher2(fa(b), len(b), fa(c), len(c))))

print("\n=== Other numbers the paper leans on ===")
print("Study B trace 6/32 vs 21/32 Fisher2 = %.2e" % fisher2(6, 32, 21, 32))
print("PNR: 4 of 4 registered inside 5-pick of 32: C(28,1)/C(32,5) = %.3e  (= 1 in %.0f)" % (comb(28, 1) / comb(32, 5), comb(32, 5) / comb(28, 1)))
# PNR items condition & code
for i in ("M034", "M038", "M068", "M091"):
    r = [x for x in rows if x["item"] == i][0]; print("  PNR", i, r["cond"], r["code"], "arm", r["arm"], "tmpl", r["tmpl"])
# residue-free C1m list (authors' list)
RF = ["M007", "M009", "M015", "M017", "M026", "M028", "M058", "M061", "M070", "M087", "M094"]
byitem = {r["item"]: r for r in rows}
print("RF list conds:", Counter(byitem[i]["cond"] for i in RF), "codes:", Counter(byitem[i]["code"] for i in RF), "tiers:", Counter(TIER[byitem[i]["tmpl"]] for i in RF))
c1_maint = [r for r in C1t if r["code"] == "M"]
print("C1m MAINTAIN total (trials):", len(c1_maint), "; C1m M by tier:", Counter(TIER[r["tmpl"]] for r in c1_maint))
print("tier sizes C1m trials:", Counter(TIER[r["tmpl"]] for r in C1t))
print("B' MAINTAIN:", sum(r['code']=='M' for r in B), " B' codes:", dict(Counter(r['code'] for r in B)))
print("M039:", byitem["M039"]["cond"], byitem["M039"]["code"], "; M078:", byitem["M078"]["cond"], byitem["M078"]["code"], "; M058:", byitem["M058"]["cond"], byitem["M058"]["code"], "; M008:", byitem["M008"]["cond"], "; ")
# D+SC+PD sensitivity ("any drift")
def anyd(rs): return sum(r["code"] in {"D", "SC", "PD"} for r in rs)
print("collapse+PD (any erosion) trials: B' %d/30 C1m %d/30 C2 %d/20 A %d/10 ; Fisher2 B' vs C1m = %.3f" % (anyd(Bt), anyd(C1t), anyd(C2t), anyd(At), fisher2(anyd(Bt), 30, anyd(C1t), 30)))
# strict-band: 23/96 is the paper's; per-condition strict codes not published
print("sealed key per-condition n:", Counter(r["cond"] for r in rows), "by arm:", Counter((r["cond"], r["arm"]) for r in rows))
print("distinct template count per cond/arm:", {(c, a): len({r['tmpl'] for r in tr if r['cond']==c and r['arm']==a}) for c in ('A','B','C1','C2') for a in (1,2) if S(tr, cond=c, arm=a)})
print("reps per template, B' trials:", Counter((r['tmpl']) for r in Bt))
