#!/usr/bin/env python3
"""Standalone verifier for the E144 exploratory organism suite (stdlib only; imports no CAIN code).

  python3 -I verify_e144_organism.py <bundle_dir|E144_ORGANISM.json>

Recomputes every summary statistic from the raw per-instance rows: n, wins/losses/ties, mean paired
difference, one-sided exact sign test in log space, bootstrap 95% CI (10,000 resamples, seed 144) and the
preregistered verdict. Also checks the preregistration commit, the row counts, the status invariants and
that no p value is displayed as 0. It cannot re-run the agent; integrity is not truth.
"""
from __future__ import annotations

import hashlib
import json
import math
import random
import sys
from pathlib import Path

THRESHOLDS = {"O1": 0.03, "O2": 0.03, "O3": 0.02, "O4": 0.05, "O5": 0.02}
REQUIRED = {"O1": 24, "O2": 24, "O3": 36, "O4": 36, "O5": 24}
RESULTS = []


def check(ok, name, detail=""):
    RESULTS.append((bool(ok), name, detail))


def mean(xs):
    return sum(xs) / len(xs) if xs else None


def lg(x):
    return math.lgamma(x) if x > 0 else 0.0


def log10_sign_p(w, l):
    n = w + l
    if n == 0:
        return 0.0
    logs = [lg(n + 1) - lg(i + 1) - lg(n - i + 1) - n * math.log(2) for i in range(w, n + 1)]
    m = max(logs)
    return round((m + math.log(sum(math.exp(x - m) for x in logs))) / math.log(10), 6)


def boot(xs, seed=144, n=10000):
    if len(xs) < 2:
        return None
    rng = random.Random(seed)
    ms = sorted(mean([xs[rng.randrange(len(xs))] for _ in range(len(xs))]) for _ in range(n))
    return [round(ms[int(0.025 * n)], 9), round(ms[int(0.975 * n) - 1], 9)]


def summary(diffs, thr, need, better="higher"):
    sgn = 1.0 if better == "higher" else -1.0
    d = [sgn * x for x in diffs]
    w = sum(1 for x in d if x > 1e-12)
    l = sum(1 for x in d if x < -1e-12)
    m = mean(d)
    if m is None:
        v = "NO DATA"
    elif len(d) < need:
        v = "UNDERPOWERED"
    elif w > l and log10_sign_p(w, l) < math.log10(0.05) and m >= thr:
        v = "SUPPORTED"
    elif w > l and log10_sign_p(w, l) < math.log10(0.05):
        v = "SUPPORTED (significant but small)"
    elif m < 0 and l > w:
        v = "NOT SUPPORTED (treatment worse)"
    else:
        v = "NOT SUPPORTED"
    return {"n": len(d), "wins": w, "losses": l, "ties": len(d) - w - l,
            "mean_diff": None if m is None else round(m, 9), "ci95": boot(d),
            "log10_p": log10_sign_p(w, l), "verdict": v}


def main() -> int:
    p = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parent)
    f = p if p.is_file() else p / "E144_ORGANISM.json"
    d = json.loads(f.read_text())
    s, rows = d["summaries"], d["studies"]
    r1, r2, r3, r4, r5 = (rows[k]["rows"] for k in ("O1", "O2", "O3", "O4", "O5"))
    rec = {
        ("O1", "prediction_aligned_minus_scratch"): summary([x["diffs"]["prediction"]["aligned-scratch"] for x in r1], 0.03, 24),
        ("O1", "prediction_aligned_minus_naive"): summary([x["diffs"]["prediction"]["aligned-naive"] for x in r1], 0.0, 24),
        ("O1", "prediction_aligned_minus_frequency"): summary([x["diffs"]["prediction"]["aligned-frequency"] for x in r1], 0.0, 24),
        ("O1", "goal_aligned_minus_scratch"): summary([x["diffs"]["goal"]["aligned-scratch"] for x in r1], 0.0, 24),
        ("O1", "goal_aligned_minus_no_model"): summary([x["diffs"]["goal"]["aligned-no_model"] for x in r1], 0.0, 24),
        ("O2", "score_capability_minus_scratch"): summary([x["diffs"]["capability-scratch"] for x in r2], 0.03, 24),
        ("O2", "score_capability_minus_retrieval"): summary([x["diffs"]["capability-retrieval"] for x in r2], 0.0, 24),
        ("O2", "score_capability_minus_random"): summary([x["diffs"]["capability-random"] for x in r2], 0.0, 24),
        ("O2", "score_capability_minus_no_world_model"): summary([x["diffs"]["capability-no_world_model"] for x in r2], 0.0, 24),
        ("O3", "sealed_full_minus_none"): summary([x["diffs"]["full-none"] for x in r3], 0.02, 36),
        ("O3", "sealed_full_minus_reset"): summary([x["diffs"]["full-reset"] for x in r3], 0.0, 36),
        ("O3", "sealed_full_minus_retrieval"): summary([x["diffs"]["full-retrieval"] for x in r3], 0.0, 36),
        ("O4", "exact_discovery_minus_random"): summary([x["diffs"]["exact:discovery-random"] for x in r4], 0.0, 36),
        ("O4", "exact_discovery_minus_random_matched"): summary([x["diffs"]["exact:discovery-random_matched"] for x in r4], 0.0, 36),
        ("O4", "prediction_discovery_minus_prior"): summary([x["diffs"]["prediction:discovery-prior"] for x in r4], 0.05, 36),
        ("O4", "prediction_discovery_minus_random_matched"): summary([x["diffs"]["prediction:discovery-random_matched"] for x in r4], 0.0, 36),
        ("O5", "heldout_collective_minus_single"): summary([x["diff"] for x in r5], 0.02, 24),
    }
    bad = []
    for (study, key), r in rec.items():
        c = s[study][key]
        if (c["n"], c["wins"], c["losses"], c["ties"], c["verdict"]) != (r["n"], r["wins"], r["losses"], r["ties"], r["verdict"]) \
                or abs(c["mean_diff"] - r["mean_diff"]) > 1e-6 or abs(c["log10_p"] - r["log10_p"]) > 1e-3 \
                or c.get("ci95") != r.get("ci95"):
            bad.append((study, key, {k: (c.get(k), r.get(k)) for k in ("n", "wins", "losses", "ties", "mean_diff", "log10_p", "verdict")}))
    check(not bad, "summaries_recompute_from_raw_rows", f"{len(rec)} contrasts; mismatches: {bad[:3]}")
    counts = {"O1": len(r1), "O2": len(r2), "O3": len(r3), "O4": len(r4), "O5": len(r5)}
    check(counts == {"O1": 24, "O2": 24, "O3": 36, "O4": 36, "O5": 24}, "registered_row_counts", json.dumps(counts))
    check(d.get("preregistration", {}).get("amendment", "").endswith("E144_PREREGISTRATION_AMENDMENT_1.md")
          and len(d["preregistration"].get("amendment_commit", "")) == 40, "preregistration_commit_recorded",
          d.get("preregistration", {}).get("amendment_commit", "")[:12])
    st = d.get("status", {})
    check(st.get("agi") == "NOT ESTABLISHED" and st.get("rsi") == "EXPERIMENTAL"
          and st.get("neural_weights_modified") is False and st.get("model_calls") == 0,
          "status_invariants", json.dumps(st))
    check(all(not (isinstance(v, dict) and "p_display" in v and str(v["p_display"]).strip() in ("0", "0.0"))
              for study in s.values() for v in study.values()), "no_zero_p_values", "")
    # diagnostic honesty: the transfer arms were identical in every O1 instance (alignment fell back to index map)
    check(all(abs(x["diffs"]["prediction"]["aligned-naive"]) < 1e-12 for x in r1),
          "O1_alignment_no_op_disclosed", "aligned == naive on every instance; reported as a limitation")
    gate = d["gates"]["gates"]
    check(set(gate) == {"O1 unified world model (prediction + planning)", "O2 capability transfer to unseen families",
                        "O3 research memory changes later behaviour", "O4 scientific discovery survives falsification",
                        "O5 verified collective vs compute-matched single"}, "five_study_gates_present", json.dumps(d["gates"]["counts"]))
    om = rec[("O4", "exact_discovery_minus_random_matched")]
    check(gate["O4 scientific discovery survives falsification"]["status"] != "PASS" and om["wins"] <= om["losses"],
          "O4_matched_control_reported_honestly",
          f"matched W/L {om['wins']}/{om['losses']}; gate {gate['O4 scientific discovery survives falsification']['status']}")
    check(bool(d.get("corrections")) and any(c.get("study") == "O4" and "matched" in c.get("what", "")
                                             for c in d.get("corrections", [])),
          "O4_correction_disclosed", "unmatched positive and matched control both recorded")
    h = hashlib.sha256(json.dumps(s, sort_keys=True, separators=(",", ":"), default=float).encode()).hexdigest()
    check(h == d.get("content_hash"), "content_hash_of_summaries", h[:16])
    for ok, name, det in RESULTS:
        print(("PASS " if ok else "FAIL ") + name + (f"  [{det}]" if det else ""))
    n_ok = sum(1 for r in RESULTS if r[0])
    print(f"\n{n_ok}/{len(RESULTS)} checks passed; {len(RESULTS) - n_ok} failed")
    return 0 if n_ok == len(RESULTS) else 1


if __name__ == "__main__":
    sys.exit(main())
