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

  python3 -I verify_e163_offline.py <bundle_dir>

Checks: manifest completeness, every file hash, Merkle root, Ed25519 signature, preregistration
commitment, experiment records, statistical reconciliation from raw rows, promotion decisions,
negative controls, evidence-chain integrity and publication-manifest consistency.

Tampering with any listed file makes verification fail.
"""
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
TIMEOUT_CHECKS = []


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


def norm(obj):
    return json.dumps(obj, sort_keys=True).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 holm(p):
    items = sorted((v, k) for k, v in p.items())
    m, out, run = len(items), {}, 0.0
    for i, (v, k) in enumerate(items):
        run = max(run, min(1.0, (m - i) * v))
        out[k] = run
    return out


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


def task_scores(rows, arm, levels):
    acc = {}
    for r in rows:
        if r["arm"] == arm and r["level"] in levels:
            acc.setdefault(r["task_id"], []).append(r["quality"])
    return {k: mean(v) for k, v in acc.items()}


def paired(a, b, ids):
    d = [a[k] - b[k] for k in ids]
    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 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_p = B / "E163_MANIFEST.json"
    if not man_p.exists():
        print("FAIL manifest missing"); return 1
    man = json.loads(man_p.read_text())
    check("status line", man.get("status") == STATUS, man.get("status"))
    sig = man.get("signature")
    body = {k: v for k, v in man.items() if k != "signature"}
    check("signature present", bool(sig))
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(sig), 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", {})
    missing = [k for k in files if not (B / k).exists()]
    check("every listed file exists", not missing, missing[:5])
    bad = []
    for k, h in files.items():
        p = B / k
        if p.exists() and hashlib.sha256(p.read_bytes()).hexdigest() != h:
            bad.append(k)
    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) - {"E163_MANIFEST.json", "E163_VERIFICATION_RESULTS.json", "PUBLICATION.json"})
    check("no unlisted file in the bundle", not unlisted, unlisted[:5])

    prereg = B / "E163_PREREGISTRATION.json"
    if prereg.exists():
        check("preregistration commitment matches", hashlib.sha256(prereg.read_bytes()).hexdigest() == man.get("preregistration_sha256"),
              man.get("preregistration_sha256"))
    else:
        check("preregistration commitment matches", False, "missing")
    audit = B / "E163_PUBLICATION_AUDIT_AT_SIGNING.json"
    check("publication audit at signing present", audit.exists() and json.loads(audit.read_text()).get("status") == "NOT_YET_PUBLISHED",
          audit.exists())
    check("no AGI/RSI establishment claim", "NOT ESTABLISHED" in json.loads((B / "E163_EXPERIMENT_SUMMARY.json").read_text()).get("status", ""),
          "status line in summary")

    # ---------------- statistical reconciliation from raw rows
    raw = B / "raw"
    sealed = load_jsonl(raw / "sealed_scores.jsonl")
    base_rows = load_jsonl(raw / "baseline_scores.jsonl")
    base = {r["task_id"]: r["quality"] for r in base_rows}
    levels = ("G1", "G2", "G3", "G4")
    arms = {}
    for a in ("P0_frozen", "P1_meta", "P2_meta2", "P1_memory", "P1_no_memory"):
        arms[a] = task_scores(sealed, a, levels)
    ids1 = sorted(set(arms["P1_meta"]) & set(base))
    h1 = paired(arms["P1_meta"], base, ids1)
    ids3 = sorted(set(arms["P1_meta"]) & set(arms["P0_frozen"]))
    ids3 = [k for k in ids3 if k in {r["task_id"] for r in sealed if r["level"] in ("G2", "G3", "G4")}]
    h3 = paired(arms["P1_meta"], arms["P0_frozen"], ids3)
    h4 = paired(arms["P2_meta2"], arms["P1_meta"], ids3)
    h8 = paired(arms["P1_memory"], arms["P1_no_memory"], ids1)
    v_arm = task_scores(sealed, "P1x_validation", levels)
    h16rc = paired(v_arm, arms["P0_frozen"], [k for k in ids3 if k in v_arm])

    coll = load_jsonl(raw / "collective_sealed.jsonl")
    c_single = task_scores(coll, "single", levels)
    c_het = task_scores(coll, "heterogeneous_k4", levels)
    h5 = paired(c_het, c_single, sorted(set(c_single) & set(c_het)))
    c_adapt = task_scores(coll, "adaptive", levels)
    fixed = {n: mean(list(task_scores(coll, n, levels).values())) for n in ("single", "homogeneous_k4", "independent_k4", "hierarchical")}
    best_fixed = max(fixed, key=fixed.get)
    c_bf = task_scores(coll, best_fixed, levels)
    h6 = paired(c_adapt, c_bf, sorted(set(c_adapt) & set(c_bf)))

    integ = load_jsonl(raw / "integration_sealed.jsonl")
    i_best = task_scores(integ, "best_individual", levels)
    i_ev = task_scores(integ, "evidence_weighted", levels)
    h7 = paired(i_ev, i_best, sorted(set(i_best) & set(i_ev)))
    h17 = json.loads((B / "E163_HYPOTHESIS_RESULTS.json").read_text()).get("hypotheses", {}).get("H17", {})
    if h17.get("best_rule"):
        best_rule = h17["best_rule"]
        i_br = task_scores(integ, best_rule, levels)
        rc17 = paired(i_br, i_best, sorted(set(i_best) & set(i_br)))
        declared17 = h17.get("rules", {}).get(best_rule, {})
        check("H17 exploratory rule reconciles", abs(declared17.get("mean_diff", 1e9) - rc17["mean_diff"]) < 2e-5,
              f"declared {declared17.get('mean_diff')} recomputed {round(rc17['mean_diff'], 6)}")
        check("H17 is labelled exploratory and post-hoc", h17.get("exploratory") is True and h17.get("post_hoc") is True)
    else:
        check("H17 exploratory rule present", False, "missing best_rule")

    causal = load_jsonl(raw / "causal.jsonl") if (raw / "causal.jsonl").exists() else []
    h11 = None
    if causal:
        def arm(n): return {r["seed"]: r["edge_f1"] for r in causal if r["arm"] == n}
        a, pv, rv = arm("active"), arm("passive"), arm("random")
        ids = sorted(set(a) & set(pv) & set(rv))
        h11 = {"active_vs_passive": paired(a, pv, ids), "active_vs_random": paired(a, rv, ids)}

    recomputed_p = {"H1": h1["p"], "H3": h3["p"], "H4": h4["p"], "H5": h5["p"], "H6": h6["p"], "H7": h7["p"], "H8": h8["p"]}
    if h11:
        recomputed_p["H11"] = max(h11["active_vs_passive"]["p"], h11["active_vs_random"]["p"])
    adj = holm(recomputed_p)

    summary = json.loads((B / "E163_EXPERIMENT_SUMMARY.json").read_text())
    hyp = json.loads((B / "E163_HYPOTHESIS_RESULTS.json").read_text())
    declared = hyp.get("verdicts", {})

    def reconcile(name, rc, declared_key=None):
        d = hyp["hypotheses"].get(declared_key or name, {})
        if not d or "mean_diff" not in d:
            check(f"{name} record present", False, "missing mean_diff")
            return
        md_ok = abs(d["mean_diff"] - rc["mean_diff"]) < 2e-5
        dir_ok = (d["mean_diff"] > 0) == (rc["mean_diff"] > 0)
        sig_ok = (rc["p"] < 0.05) == (d["p_one_sided"] < 0.05) or abs(rc["p"] - d["p_one_sided"]) < 0.08
        check(f"{name} mean difference reconciles", md_ok, f"declared {d['mean_diff']} recomputed {round(rc['mean_diff'],6)}")
        check(f"{name} direction reconciles", dir_ok)
        check(f"{name} significance reconciles", sig_ok, f"declared p {d['p_one_sided']} recomputed p {rc['p']}")
        check(f"{name} wins/losses reconcile", (d.get("wins"), d.get("losses")) == (rc["wins"], rc["losses"]),
              f"declared {d.get('wins')}/{d.get('losses')} recomputed {rc['wins']}/{rc['losses']}")

    reconcile("H1", h1)
    reconcile("H3", h3)
    reconcile("H4", h4)
    reconcile("H8", h8)
    reconcile("H5", h5)
    reconcile("H6", h6)
    reconcile("H7", h7)
    reconcile("H16", h16rc)
    if h11:
        check("H11 direction reconciles", summary["hypotheses"]["H11"]["active_beats_both"] ==
              (h11["active_vs_passive"]["mean_diff"] > 0 and h11["active_vs_random"]["mean_diff"] > 0))

    # negative controls
    check("memory poison never retrieved as verified", summary.get("poison_retrieved_verified") is False)
    sc = summary["hypotheses"]["H12"]["shortcut"]
    check("planted shortcut diagnostic recorded", "pooled_rule_selects" in sc and "worst_rule_selects" in sc)
    check("compute matched across proposer arms",
          len({r["spent_evals"] for r in load_jsonl(raw / "campaigns.jsonl") if r["arm"] != "P0_4x"}) == 1)
    check("meta cost separated from campaign cost", "meta_cost_evals" in summary["compute"])
    check("promotion decision recorded and not confused with a sealed claim",
          summary["lineage"][-1].get("accepted") in (True, False) and ("H3" in declared))
    check("governance report present", (B / "E163_GOVERNANCE_REPORT.json").exists())
    if (B / "E163_GOVERNANCE_REPORT.json").exists():
        g = json.loads((B / "E163_GOVERNANCE_REPORT.json").read_text())
        check("governance suite passed", g.get("passed") == g.get("total"), f"{g.get('passed')}/{g.get('total')}")
    check("H15 verdict present", declared.get("H15") in ("SUPPORTED", "FAILED"), declared.get("H15"))
    check("H14 verdict present", declared.get("H14") in ("SUPPORTED", "FAILED"), declared.get("H14"))

    # evidence chain: each raw row count > 0 and task ids unique per level/arm/seed
    check("raw sealed rows present", len(sealed) > 0, len(sealed))
    keys = [(r["arm"], r["seed"], r["task_id"]) for r in sealed]
    check("no duplicate sealed rows", len(keys) == len(set(keys)))
    check("every sealed task has a baseline score", all(r["task_id"] in base for r in sealed))

    # publication manifest consistency (optional, outside the signature)
    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 (not yet published)", True, "PUBLICATION.json absent: pre-publication bundle")

    ok = all(c["ok"] for c in checks)
    out = {"schema": "cain42.e163.verify.v1", "bundle": str(B), "checks": len(checks), "passed": sum(c["ok"] for c in checks),
           "failed": [c for c in checks if not c["ok"]], "ok": ok,
           "recomputed": {"H1": h1, "H3": h3, "H4": h4, "H5": h5, "H6": h6, "H7": h7, "H8": h8, "H11": h11, "holm": adj}}
    print(json.dumps({k: out[k] for k in ("checks", "passed", "ok")}))
    for c in out["failed"]:
        print("FAIL", c["check"], c["detail"])
    return 0 if ok else 1


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