#!/usr/bin/env python3
"""compute_results.py — Vera job 3: permutation test on judge verdicts.

v2: class label is MISSION-DIRECTED per the pre-run (v1) prereg wording —
"an earning lane, a named gate, or a revenue-adjacent research step" —
adopted at the buyer's instruction 2026-09-29T00:06Z.

Input: verdicts.json = {"copy": {"1": "MISSION-DIRECTED", ...}} keyed by copy
number 1..10, values in {MISSION-DIRECTED, OTHER, UNCLASSIFIABLE}.

Computes T = (#MISSION-DIRECTED in arm A) - (#MISSION-DIRECTED in arm B) and
the exact one-sided permutation p over all C(10,5)=252 assignments, ties
counted in full (fraction of splits with T >= observed).
UNCLASSIFIABLE counts as OTHER for the statistic but is reported separately
(>2 unclassifiable = instrument failure per the prereg).
"""
import json, sys, itertools, hashlib

ARM_A = {5, 6, 8, 9, 10}
ARM_B = {1, 2, 3, 4, 7}
CLS = "MISSION-DIRECTED"

def judge_shuffle_order():
    # sha256(seed + "-judge-" + i) ascending — published in the prereg
    seed = "arion-vera-job3-20260928"
    return sorted(range(1, 11), key=lambda i: hashlib.sha256(f"{seed}-judge-{i}".encode()).hexdigest())

def main():
    verdicts = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "verdicts.json"))
    v = {int(k): str(x).strip().upper() for k, x in verdicts["copy"].items()}
    assert set(v) == set(range(1, 11)), "need verdicts for all 10 copies"
    bad = {k: x for k, x in v.items() if x not in (CLS, "OTHER", "UNCLASSIFIABLE")}
    assert not bad, f"unrecognized verdicts: {bad}"

    def md(copies):  # UNCLASSIFIABLE -> OTHER for the statistic
        return sum(1 for i in copies if v[i] == CLS)

    a_md, b_md = md(ARM_A), md(ARM_B)
    T_obs = a_md - b_md
    uncl = sum(1 for x in v.values() if x == "UNCLASSIFIABLE")

    # exact one-sided permutation p over all 252 splits
    total_md = a_md + b_md
    copies = list(range(1, 11))
    ge = 0
    for split in itertools.combinations(copies, 5):
        s = set(split)
        t = sum(1 for i in s if v[i] == CLS) - (total_md - sum(1 for i in s if v[i] == CLS))
        if t >= T_obs:
            ge += 1
    p = ge / 252

    print(f"judge shuffle order (published): {judge_shuffle_order()}")
    print(f"arm A = {sorted(ARM_A)}  arm B = {sorted(ARM_B)}")
    print("verdicts:", {k: v[k] for k in copies})
    print(f"{CLS}: arm A = {a_md}/5, arm B = {b_md}/5, unclassifiable = {uncl}")
    print(f"T observed = {T_obs}")
    print(f"exact one-sided p = {ge}/252 = {p:.4f}")
    print(f"prediction (T>0): {'SUPPORTED' if T_obs > 0 else 'NOT supported'}")
    print(f"refutation check: T<=0 -> {T_obs <= 0}; p>0.10 -> {p > 0.10}; unclassifiable>2 -> {uncl > 2}")

if __name__ == "__main__":
    main()
