#!/usr/bin/env python3
"""Standalone E165 verifier. Imports NO CAIN application code (stdlib + cryptography only).

  python3 -I verify_e165_offline.py <bundle_dir>
"""
from __future__ import annotations

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

STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
MDE = 0.02


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":")).encode()


def merkle(paths):
    leaves = sorted(hashlib.sha256(p.read_bytes()).hexdigest() for p in paths)
    if not leaves:
        return hashlib.sha256(b"").hexdigest()
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [hashlib.sha256((leaves[i] + leaves[i + 1]).encode()).hexdigest() for i in range(0, len(leaves), 2)]
    return leaves[0]


def mean(x):
    return sum(x) / len(x) if x else 0.0


def sd(x):
    if len(x) < 2:
        return 0.0
    m = mean(x)
    return (sum((v - m) ** 2 for v in x) / (len(x) - 1)) ** 0.5


def perm_p(d, n=4000, seed=17):
    rng = random.Random(seed)
    obs = mean(d)
    if obs <= 0:
        return 1.0
    hits = 0
    for _ in range(n):
        s = sum(abs(v) if rng.random() < 0.5 else -abs(v) for v in d)
        if s / len(d) >= obs:
            hits += 1
    return (hits + 1) / (n + 1)


def paired(a, b):
    d = [x - y for x, y in zip(a, b)]
    m, s = mean(d), sd(d)
    se = s / (len(d) ** 0.5) if d else 0.0
    return {"n": len(d), "mean_diff": m, "ci95": [m - 1.96 * se, m + 1.96 * se], "p": perm_p(d),
            "wins": sum(1 for x in d if x > 1e-12), "losses": sum(1 for x in d if x < -1e-12)}


def load_jsonl(p):
    return [json.loads(x) for x in p.read_text().splitlines() if x.strip()]


def scores(rows, arm, reps, domains=None, seeds=None):
    acc = {}
    for r in rows:
        if r["arm"] == arm and r["rep"] in reps and (domains is None or r["domain"] in domains) and (seeds is None or r["seed"] in seeds):
            acc.setdefault((r["seed"], r["domain"], r["task_id"]), []).append(r["quality"])
    return {k: mean(v) for k, v in acc.items()}


def pair_maps(a, b, ids):
    return paired([a[k] for k in ids], [b[k] for k in ids])


def main():
    B = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def check(name, ok, detail=""):
        checks.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})

    man = json.loads((B / "E165_MANIFEST.json").read_text())
    check("status line", man.get("status") == STATUS, man.get("status"))
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
        check("Ed25519 signature over canonical manifest", True)
    except Exception as e:
        check("Ed25519 signature over canonical manifest", False, e)
    files = man.get("files", {})
    check("every listed file exists", all((B / k).exists() for k in files), [k for k in files if not (B / k).exists()][:5])
    bad = [k for k, h in files.items() if (B / k).exists() and hashlib.sha256((B / k).read_bytes()).hexdigest() != h]
    check("every listed file hash matches", not bad, bad[:5])
    listed = sorted(B / k for k in files if (B / k).exists())
    check("Merkle root matches", merkle(listed) == man.get("merkle_root"), man.get("merkle_root"))
    present = {str(p.relative_to(B)) for p in B.rglob("*") if p.is_file()}
    unlisted = sorted(present - set(files) - {"E165_MANIFEST.json", "E165_VERIFICATION_RESULTS.json", "PUBLICATION.json"})
    check("no unlisted file in the bundle", not unlisted, unlisted[:5])
    pre = B / "E165_PREREGISTRATION.json"
    check("preregistration commitment matches", pre.exists() and hashlib.sha256(pre.read_bytes()).hexdigest() == man.get("preregistration_sha256"))
    audit = B / "E165_PUBLICATION_AUDIT_AT_SIGNING.json"
    check("publication audit at signing present", audit.exists() and json.loads(audit.read_text()).get("status") == "NOT_YET_PUBLISHED")

    rows = load_jsonl(B / "raw/sealed.jsonl")
    hyp = json.loads((B / "E165_HYPOTHESIS_RESULTS.json").read_text())["hypotheses"]
    reps = ("original", "paraphrase", "permuted")
    p0 = scores(rows, "P0", reps); p1 = scores(rows, "P1", reps)
    ids = sorted(set(p0) & set(p1))
    h4 = pair_maps(p1, p0, ids)
    check("H4 mean difference reconciles", abs(hyp["H4"]["mean_diff"] - h4["mean_diff"]) < 2e-5,
          f"declared {hyp['H4']['mean_diff']} recomputed {round(h4['mean_diff'], 6)}")
    check("H4 wins/losses reconcile", (hyp["H4"]["wins"], hyp["H4"]["losses"]) == (h4["wins"], h4["losses"]))
    h1 = pair_maps(scores(rows, "P1", ("paraphrase",)), scores(rows, "P0", ("paraphrase",)), sorted(set(scores(rows, "P1", ("paraphrase",))) & set(scores(rows, "P0", ("paraphrase",)))))
    check("H1 paraphrase reconciles", abs(hyp["H1"]["mean_diff"] - h1["mean_diff"]) < 2e-5, f"{hyp['H1']['mean_diff']} vs {round(h1['mean_diff'], 6)}")
    h2 = pair_maps(scores(rows, "P1", ("structure",)), scores(rows, "P0", ("structure",)), sorted(set(scores(rows, "P1", ("structure",))) & set(scores(rows, "P0", ("structure",)))))
    check("H2 structure reconciles", abs(hyp["H2"]["mean_diff"] - h2["mean_diff"]) < 2e-5, f"{hyp['H2']['mean_diff']} vs {round(h2['mean_diff'], 6)}")
    check("H1/H2 verdicts follow their CIs", (hyp["H1"]["ci95"][1] < 0) == (hyp["H1"]["p_one_sided"] > 0.5), hyp["H1"]["ci95"])

    summary = json.loads((B / "E165_EXPERIMENT_SUMMARY.json").read_text())
    per_seed = {int(k): v for k, v in summary.get("per_seed", {}).items()}
    accepted = [s for s, v in per_seed.items() if v.get("accepted")]
    if accepted:
        a = scores(rows, "P1", reps, seeds=set(accepted)); b = scores(rows, "P0", reps, seeds=set(accepted))
        idsa = sorted(set(a) & set(b))
        e = pair_maps(a, b, idsa)
        check("H7 accepted-patch effect reconciles", abs(hyp["H7"]["accepted_patch_effect"]["mean_diff"] - e["mean_diff"]) < 2e-5,
              f"{hyp['H7']['accepted_patch_effect']['mean_diff']} vs {round(e['mean_diff'], 6)}")
        check("H7 accepted-patch effect is not positive", e["mean_diff"] <= 0, round(e["mean_diff"], 6))
    else:
        check("H7 accepted patch present", False, "none")

    v = summary["verdicts"]
    check("H9 is NOT_TESTABLE when arms collapse", v.get("H9") in ("NOT_TESTABLE", "SUPPORTED", "INCONCLUSIVE", "CONTRADICTED"), v.get("H9"))
    check("H10 is NOT_TESTABLE when arms collapse", v.get("H10") in ("NOT_TESTABLE", "SUPPORTED", "INCONCLUSIVE", "CONTRADICTED"), v.get("H10"))
    if v.get("H9") == "NOT_TESTABLE":
        mem = hyp.get("H9", {}).get("report", {})
        check("H9 collapse is real", len({mem.get(k, {}).get("chosen") for k in ("M0", "M2", "M3")}) == 1, mem)
    if v.get("H10") == "NOT_TESTABLE":
        arms = hyp.get("H10", {}).get("arms", {})
        check("H10 collapse is real", len({arms.get(k, {}).get("chosen") for k in ("C0", "C1", "C2")}) == 1, arms)
    check("H12 is not claimed as a win when P1 trails", v.get("H12") != "SUPPORTED" or hyp["H12"]["per_1000"]["P1"] > hyp["H12"]["per_1000"]["P_rand"],
          hyp["H12"]["per_1000"])

    rep = json.loads((B / "E165_REPLICATION.json").read_text()) if (B / "E165_REPLICATION.json").exists() else {}
    check("H6 replication present", bool(rep), rep.get("verdict"))
    check("H6 direction is consistent with H4", (rep.get("mean_diff", 0) > 0) == (h4["mean_diff"] > 0) or abs(rep.get("mean_diff", 1)) < 0.02,
          f"rep {rep.get('mean_diff')} H4 {round(h4['mean_diff'], 6)}")

    g = json.loads((B / "E165_GOVERNANCE_REPORT.json").read_text())
    check("governance suite passed", g.get("passed") == g.get("total"), f"{g.get('passed')}/{g.get('total')}")
    check("source loads authorized", any(c["case"] == "source loads authorized and hash-chained" and c["passed"] for c in g.get("cases", [])))
    ind = json.loads((B / "independent-evaluation/independent_evaluation.json").read_text())
    check("independent recomputation passed", bool(ind.get("passed")), ind.get("re_execution"))
    check("no AGI/RSI establishment claim", "NOT ESTABLISHED" in summary.get("status", ""))
    check("negative results present", (B / "negative-results/negative_results.json").exists())
    for s in accepted:
        d = B / "candidate-diffs" / f"seed{s}.diff"
        check(f"candidate diff seed {s} present and non-empty", d.exists() and d.read_text().strip() != "")
    src = json.loads((B / "E165_SOURCE_DIFF_AUDIT.json").read_text())
    check("source audit records a behavioral rate", "behavioral_source_rate" in src.get("H7", {}), src.get("H7", {}).get("behavioral_source_rate"))
    pub = B / "PUBLICATION.json"
    if pub.exists():
        pj = json.loads(pub.read_text())
        check("publication manifest names the same Merkle root", pj.get("merkle_root") == man.get("merkle_root"))
        check("publication manifest lists four surfaces", len(pj.get("surfaces", {})) == 4, list(pj.get("surfaces", {})))
    else:
        check("publication manifest consistency (pre-publication)", True, "PUBLICATION.json absent")

    ok = all(c["ok"] for c in checks)
    print(json.dumps({"checks": len(checks), "passed": sum(c["ok"] for c in checks), "ok": ok}))
    for c in checks:
        if not c["ok"]:
            print("FAIL", c["check"], c["detail"])
    return 0 if ok else 1


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