#!/usr/bin/env python3
"""E157 standalone offline verifier.

Imports no CAIN code: stdlib + cryptography only. Recomputes file hashes, Merkle root,
Ed25519 signature, preregistration hash, salt commitment, primary statistics, lineage,
gate consistency, security counts and claim-to-evidence consistency. Tamper is rejected.

Usage: python3 -I verify_e157_offline.py [bundle_dir]

v2 (source withdrawal): procedure source was withdrawn from public view; the original
signed v1 manifest (MANIFEST_V1_ORIGINAL.json) is the SHA-256 commitment to it.
"""
import hashlib
import json
import math
import re
import sys
from pathlib import Path

B = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
C = []


def check(name, ok, detail=""):
    C.append(bool(ok))
    print(("PASS " if ok else "FAIL ") + name + (f"  [{detail}]" if detail else ""))


def sha(b):
    if isinstance(b, str):
        b = b.encode()
    return hashlib.sha256(b).hexdigest()


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


def load(rel):
    return json.loads((B / rel).read_text())


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 math.sqrt(sum((v - m) ** 2 for v in x) / (len(x) - 1))


def _betacf(a, b, x):
    qab, qap, qam, c, d = a + b, a + 1, a - 1, 1.0, 1 - (a + b) * x / (a + 1)
    d = 1 / (d if abs(d) > 1e-300 else 1e-300); h = d
    for m in range(1, 200):
        m2 = 2 * m
        for aa in (m * (b - m) * x / ((qam + m2) * (a + m2)), -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))):
            d = 1 + aa * d; d = 1 / (d if abs(d) > 1e-300 else 1e-300)
            c = 1 + aa / c if abs(1 + aa / c) > 1e-300 else 1e-300
            h *= d * c
    return h


def t_sf(t, df):
    x = df / (df + t * t)
    a, b = df / 2, 0.5
    front = math.exp(math.lgamma((df + 1) / 2) - math.lgamma(df / 2) - math.lgamma(0.5) + a * math.log(x) + b * math.log(1 - x))
    ib = front * _betacf(a, b, x) / a if x < (a + 1) / (a + b + 2) else 1 - front * _betacf(b, a, 1 - x) / b
    return ib / 2 if t > 0 else 1 - ib / 2


def paired(rows_a, rows_b, field="hidden_gain"):
    A = {r["problem_key"]: r for r in rows_a}
    Bb = {r["problem_key"]: r for r in rows_b}
    k = sorted(set(A) & set(Bb))
    d = [A[x][field] - Bb[x][field] for x in k]
    n = len(d); m = mean(d); s = sd(d)
    t = m / (s / math.sqrt(n)) if s > 0 else 0.0
    p = t_sf(t, n - 1) if n > 1 else 1.0
    return {"n": n, "mean": m, "sd": s, "t": t, "p": p}


def close(a, b, tol=1e-6):
    return a is not None and b is not None and abs(float(a) - float(b)) <= tol


def main():
    if not (B / "MANIFEST.json").exists():
        print("FAIL manifest missing"); print("0/1 checks passed"); return 1
    man = load("MANIFEST.json")
    check("manifest schema", man.get("schema") in ("cain42.e157.manifest.v1", "cain42.e157.manifest.v2"), man.get("schema"))
    v2 = man.get("schema") == "cain42.e157.manifest.v2"

    def merkle(fs):
        L = [bytes.fromhex(sha((f + ":" + fs[f]).encode())) for f in sorted(fs)]
        while len(L) > 1:
            L = [hashlib.sha256(L[i] + (L[i + 1] if i + 1 < len(L) else L[i])).digest() for i in range(0, len(L), 2)]
        return L[0].hex() if L else sha(b"")

    def sig_ok(m):
        try:
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
            pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(m["pubkey_ed25519"]))
            pub.verify(bytes.fromhex(m["signature"]), canon({k: v for k, v in m.items() if k != "signature"}).encode())
            return True, m["pubkey_fingerprint"]
        except Exception as e:
            return False, type(e).__name__

    # ---- file hashes and no extra files
    files = man.get("files", {})
    present = {str(p.relative_to(B)) for p in B.rglob("*") if p.is_file()}
    allowed = set(files) | {"MANIFEST.json", "MERKLE_ROOT.txt", "E157_MANIFEST.json", "E157_MERKLE_ROOT.txt"}
    missing = [f for f in files if not (B / f).exists()]
    bad = [f for f, h in files.items() if (B / f).exists() and sha((B / f).read_bytes()) != h]
    check("all manifest files present", not missing, f"{len(files)} files, missing={len(missing)}")
    check("all file SHA-256 match", not bad, f"mismatch={len(bad)}")
    check("no unmanifested files", present <= allowed, f"extra={sorted(present - allowed)[:3]}")

    # ---- Merkle + signature
    root = merkle(files)
    check("Merkle root recomputes", root == man.get("merkle_root") == (B / "MERKLE_ROOT.txt").read_text().strip(), root[:16])
    ok_sig, detail = sig_ok(man)
    check("Ed25519 signature verifies", ok_sig, detail)

    # ---- source withdrawal (v2): the original signed v1 manifest is the commitment to withdrawn source
    COMMIT = {}
    if v2:
        v1 = load("MANIFEST_V1_ORIGINAL.json")
        ok1, d1 = sig_ok(v1)
        check("original v1 manifest signature verifies", ok1 and v1["pubkey_ed25519"] == man["pubkey_ed25519"], d1)
        r1 = merkle(v1["files"])
        check("original v1 Merkle root recomputes", r1 == v1["merkle_root"] == man.get("supersedes_merkle_root")
              == (B / "MERKLE_ROOT_V1_ORIGINAL.txt").read_text().strip(), r1[:16])
        wd = load("WITHDRAWN_SOURCE.json")
        COMMIT = {w["path"]: w["sha256"] for w in wd["files"]}
        check("withdrawn files are committed in v1 and absent now",
              all(v1["files"].get(p) == h and not (B / p).exists() for p, h in COMMIT.items()) and len(COMMIT) == man.get("withdrawn_source"),
              f"{len(COMMIT)} withdrawn")
        kept = {f: h for f, h in v1["files"].items() if f not in COMMIT and f in files and f != "verify_e157_offline.py"}
        check("every other v1 file is unchanged in v2",
              all(files[f] == h for f, h in kept.items()) and set(v1["files"]) - set(COMMIT) - {"verify_e157_offline.py"} <= set(files),
              f"{len(kept)} unchanged")
        man_v1_fields = {k: v1[k] for k in ("preregistration_hash", "salt_commitment", "source_commit", "claims")}
        check("v2 carries the v1 claims and commitments unchanged", all(man.get(k) == v for k, v in man_v1_fields.items()))

    # ---- preregistration
    pre = load("hypothesis_preregistration.json")
    stored = pre.pop("preregistration_hash", None)
    recomputed = sha(canon(pre))
    check("preregistration hash recomputes", stored == recomputed == man.get("preregistration_hash"), (stored or "")[:16])
    check("status line present", pre.get("status") == {"AGI": "NOT ESTABLISHED", "RSI": "EXPERIMENTAL"}, pre.get("status"))

    # ---- salt reveal
    reveal = (B / "SEALED_SALT_REVEALED.txt").read_text().strip() if (B / "SEALED_SALT_REVEALED.txt").exists() else None
    check("sealed salt reveals to the committed hash", reveal is not None and sha(reveal) == pre["salt_commitment"]["sha256"], (reveal or "")[:8])

    # ---- mandatory artifacts
    required = ["FORENSIC_BASELINE.md", "capability_inventory.json", "evidence_reconciliation.json", "e154_e155_e156_audit.json",
                "research_literature.json", "research_direction_log.json", "hypothesis_preregistration.json", "experiment_registry.json",
                "experiment_results.jsonl", "agent_contributions.jsonl", "anthropic_request_ledger.jsonl", "algorithm_candidates.json",
                "research_memory_report.json", "cross_domain_transfer_report.json", "successor_lineage.json", "capability_retention.json",
                "recursive_improvement_report.json", "scientific_discoveries.json", "negative_results.json", "regression_report.json",
                "security_report.json", "governance_report.json", "resource_usage.json", "independent_evaluation.json",
                "public_publication_audit.json", "E157_FINAL_REPORT.md", "E157_EXECUTIVE_SUMMARY.md", "E157_GATE_MATRIX.json",
                "E157_RESULTS.json", "REPRODUCE.md"]
    miss = [f for f in required if not (B / f).exists()]
    check("mandatory artifacts present", not miss, f"missing={miss}")

    # ---- results and statistics
    res = load("E157_RESULTS.json")
    Bt = res["tracks"]["B"]
    check("primary trial count", len(Bt["rows"]["random"]) == 150 and len(Bt["rows"]["sweep"]) == 150,
          f"{len(Bt['rows']['random'])}/{len(Bt['rows']['sweep'])}")
    for arm in ("random", "sweep", "early", "contextual", "model_prior"):
        rows = Bt["rows"][arm]
        m = mean([r["hidden_gain"] for r in rows])
        check(f"mean hidden gain recomputes: {arm}", close(m, Bt["arms"][arm]["mean_hidden_gain"]), f"{m:.6f}")
        vr = mean([1.0 if r["valid_improvement"] else 0.0 for r in rows])
        check(f"valid rate recomputes: {arm}", close(vr, Bt["arms"][arm]["valid_rate"]), f"{vr:.6f}")
        keys = [r["problem_key"] for r in rows]
        check(f"no duplicate problems: {arm}", len(keys) == len(set(keys)), f"{len(keys)}")
    p = paired(Bt["rows"]["sweep"], Bt["rows"]["random"])
    stored_p = Bt["vs_random"]["sweep"]
    check("G1 paired mean difference recomputes", close(p["mean"], stored_p["mean_diff"]), f"{p['mean']:.6f}")
    check("G1 paired p recomputes", close(p["p"], stored_p["p_one_sided"], 1e-6), f"{p['p']:.3e}")
    check("G1 accepted is consistent with evidence", (p["mean"] > 0 and p["p"] <= 0.05) == (load("successor_lineage.json")["generations"][1]["status"] == "ACCEPTED"),
          f"diff={p['mean']:.4f} p={p['p']:.3e}")

    # ---- lineage
    lin = load("successor_lineage.json")
    gens = lin["generations"]
    check("lineage has G0-G3", [g["generation"] for g in gens] == ["G0", "G1", "G2", "G3"])
    parent_ok = gens[1]["parent"] == "G0" and gens[2]["parent"] == "G1" and gens[3]["parent"] == "G2"
    check("parent chain is intact", parent_ok)
    src_ok = True
    for g in gens:
        rel = f"procedure_{g['policy']}.py"
        pth = B / rel
        if rel in COMMIT:
            src_ok = src_ok and COMMIT[rel] == g["source_sha256"]
        else:
            src_ok = src_ok and pth.exists() and sha(pth.read_bytes()) == g["source_sha256"]
    check("generation source hashes match rendered source", src_ok)

    # ---- memory / transfer / collective / retention
    D = res["tracks"]["D"]
    for v in ("M0_none", "M2_evidence", "M4_hierarchical"):
        m = mean([r["hidden_gain"] for r in D["rows"][v]])
        check(f"memory mean recomputes: {v}", close(m, D["arms"][v]["mean_hidden_gain"]), f"{m:.6f}")
    mem = load("research_memory_report.json")
    check("memory poison defect recorded", mem["quarantine_check"]["poisoned_prior"]["M2_evidence"] > 0.8, "M2 prior>0.8")
    check("memory quarantine correction recorded", mem["quarantine_check"]["poisoned_prior"]["M4_hierarchical"] < 0.6, "M4 prior<0.6")
    tr = load("cross_domain_transfer_report.json")
    check("transfer report has a sign", tr.get("transfer_vs_scratch", {}).get("mean_diff") is not None, str(tr.get("transfer_vs_scratch", {}).get("mean_diff")))
    col = res["tracks"]["collective"]
    check("collective used distinct worker PIDs", col["collective"]["distinct_pids"] >= 3, f"{col['collective']['distinct_pids']}")
    ret = load("capability_retention.json")
    check("retention evaluated for all generations", set(ret["generations"]) == {"random", "sweep", "early", "failure_aware"})

    # ---- gates and security
    gates = load("E157_GATE_MATRIX.json")["gates"]
    check("24 promotion gates present", len(gates) == 24, f"{len(gates)}")
    sec = load("security_report.json")
    check("security totals sum", sec["blocked"] + sec["bypassed"] + sec.get("defects_observed", 0) == sec["total"], f"{sec['total']}")
    check("no security bypass", sec["bypassed"] == 0, f"{sec['bypassed']}")
    if (B / "tamper_results.json").exists():
        tam = load("tamper_results.json")
        check("all tamper fixtures rejected", len(tam["fixtures"]) >= 4 and all(not x["verifier_ok"] for x in tam["fixtures"]), f"{len(tam['fixtures'])} fixtures")

    # ---- key leakage
    leak = []
    for pth in B.rglob("*"):
        if pth.is_file() and pth.suffix in (".json", ".md", ".txt", ".jsonl", ".py"):
            try:
                if re.search(r"sk-ant-[A-Za-z0-9_-]{12,}", pth.read_text(errors="ignore")):
                    leak.append(str(pth.relative_to(B)))
            except Exception:
                pass
    check("no Anthropic key material in the bundle", not leak, f"{leak[:3]}")

    # ---- claim audit
    forbidden = ["AGI achieved", "achieved AGI", "AGI-certified", "unrestricted RSI", "third-party verified", "SOC 2 certified",
                 "ISO 42001 certified", "court-admissible", "production-ready", "SLSA Level 3", "hardware-attested"]
    bad_claims = []
    for name in ("E157_FINAL_REPORT.md", "E157_EXECUTIVE_SUMMARY.md", "FORENSIC_BASELINE.md"):
        if not (B / name).exists():
            continue
        text = (B / name).read_text()
        for ph in forbidden:
            for m in re.finditer(re.escape(ph), text, re.I):
                pre = text[max(0, m.start() - 70):m.start()].lower()
                if not re.search(r"\b(no|not|never|without|neither|cannot|does not|did not|is not|are not)\b", pre):
                    bad_claims.append(f"{name}:{ph}")
    check("no unnegated overclaim in public prose", not bad_claims, f"{bad_claims[:4]}")

    # ---- manifest claims point at existing evidence and use allowed statuses
    claims = man.get("claims", [])
    allowed_status = {"SUPPORTED", "PARTIAL", "NEGATIVE", "NOT_CLAIMED", "BLOCKED"}
    ok_claims = all(c.get("status") in allowed_status and (B / c.get("evidence", "")).exists() for c in claims)
    check("manifest claims use allowed statuses and existing evidence", ok_claims and len(claims) >= 4, f"{len(claims)} claims")

    print(f"{sum(C)}/{len(C)} checks passed")
    return 0 if all(C) else 1


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