#!/usr/bin/env python3
"""Standalone verifier for E144 O6 (mathematical law discovery), stdlib only.

  python3 -I verify_e144_math.py <bundle_dir|E144_MATH.json>
"""
from __future__ import annotations

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

R = []


def check(ok, name, det=""):
    R.append((bool(ok), name, det))


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 lp(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 summarize(d, thr, need):
    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 len(d) < need:
        v = "UNDERPOWERED"
    elif w > l and lp(w, l) < math.log10(0.05) and m >= thr:
        v = "SUPPORTED"
    elif w > l and lp(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": round(m, 9),
            "ci95": boot(d), "log10_p": lp(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_MATH.json"
    d = json.loads(f.read_text())
    rows, s = d["rows"], d["summaries"]
    a = summarize([x["diffs"]["exact:discovery-random"] for x in rows], 0.0, 36)
    b = summarize([x["diffs"]["prediction:discovery-prior"] for x in rows], 0.05, 36)
    bad = []
    for key, r in (("exact_discovery_minus_random", a), ("prediction_discovery_minus_prior", b)):
        c = s[key]
        if (c["n"], c["wins"], c["losses"], c["ties"], c["verdict"], c["mean_diff"], c["log10_p"]) != \
           (r["n"], r["wins"], r["losses"], r["ties"], r["verdict"], r["mean_diff"], r["log10_p"]):
            bad.append((key, c, r))
    check(not bad, "summaries_recompute_from_rows", str(bad[:1]))
    check(len(rows) == 36, "registered_row_count", str(len(rows)))
    er = {arm: round(sum(x["scores"][arm]["exact"] for x in rows) / len(rows), 6) for arm in ("discovery", "random", "prior")}
    check(er == s["exact_rate"], "exact_rates_recompute", json.dumps(er))
    check(er["discovery"] == 1.0 and er["random"] == 1.0,
          "active_design_tie_reported_as_negative", "discovery and random both recover every law; verdict is NOT SUPPORTED")
    pr = d.get("preregistration", {})
    check(pr.get("amendment", "").endswith("E144_PREREGISTRATION_AMENDMENT_2.md") and len(pr.get("amendment_commit", "")) == 40,
          "preregistration_commit", pr.get("amendment_commit", "")[:12])
    st = d.get("status", {})
    check(st.get("agi") == "NOT ESTABLISHED" and st.get("rsi") == "EXPERIMENTAL" and st.get("model_calls") == 0,
          "status_invariants", json.dumps(st))
    for ok, name, det in R:
        print(("PASS " if ok else "FAIL ") + name + (f"  [{det}]" if det else ""))
    n = sum(1 for x in R if x[0])
    print(f"\n{n}/{len(R)} checks passed; {len(R) - n} failed")
    return 0 if n == len(R) else 1


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