#!/usr/bin/env python3
"""PRC standalone auditor — re-derives every campaign from the revealed salts. No CAIN imports.

Rebuilds the truth probabilities, every draw, all five analyses, the compliance verdict, every
aggregate, hypothesis and the final verdict; verifies the signed contract precedes every result,
every Ed25519 signature and SHA-256 link of the governed memory, and the signed manifest.

Usage: python3 verify_prc_offline.py <bundle-dir>
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

CAMPAIGNS, NULLS, N = 40, 20, 60
P_NULL, P_REAL_LO, P_REAL_HI = 0.50, 0.60, 0.70
THETA_NAIVE, THETA_CONTRACT = 0.55, 0.6062
CHECKPOINTS = (10, 20, 30, 40, 50, 60)
SUBSETS = {"all": tuple(range(60)), "first30": tuple(range(30)), "last30": tuple(range(30, 60)),
           "odd": tuple(range(0, 60, 2)), "even": tuple(range(1, 60, 2))}
ARMS = ("NONE", "CONTRACT", "SUBSET", "PEEK", "ORACLE")
TENANT, SEED = "cain42-prc", "prc"


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


def sha(b):
    return hashlib.sha256(b).hexdigest()


def h(s):
    return hashlib.sha256(s.encode()).hexdigest()


def unit(salt, *parts):
    return int(h("|".join((salt, *map(str, parts))))[:8], 16) / float(1 << 32)


def truth_p(salt, c):
    if c < NULLS:
        return P_NULL
    return round(P_REAL_LO + (P_REAL_HI - P_REAL_LO) * unit(salt, "p", c), 6)


def draws(salt, c):
    p = truth_p(salt, c)
    return [unit(salt, "x", c, i) < p for i in range(N)]


def mean(xs):
    return sum(1 for x in xs if x) / len(xs) if xs else 0.0


def decide(xs, arm, p):
    overall = mean(xs)
    d = {"arm": arm, "n_used": len(xs), "statistic": "overall_rate", "theta": THETA_NAIVE,
         "mean": round(overall, 6), "promote": False}
    if arm == "NONE":
        d["promote"] = overall >= THETA_NAIVE
    elif arm == "CONTRACT":
        d.update({"n_used": N, "statistic": "overall_rate", "theta": THETA_CONTRACT})
        d["promote"] = overall >= THETA_CONTRACT
    elif arm == "SUBSET":
        best, name = -1.0, "all"
        for k, idx in SUBSETS.items():
            m = mean([xs[i] for i in idx])
            if m > best:
                best, name = m, k
        d.update({"statistic": f"subset:{name}", "n_used": len(SUBSETS[name]),
                  "mean": round(best, 6), "promote": best >= THETA_NAIVE})
    elif arm == "PEEK":
        best, best_k = -1.0, 0
        for k in CHECKPOINTS:
            m = mean(xs[:k])
            if m > best:
                best, best_k = m, k
            if m >= THETA_NAIVE:
                d.update({"promote": True, "n_used": k, "mean": round(m, 6)})
                break
        if not d["promote"]:
            d.update({"n_used": N, "mean": round(best, 6)})
    elif arm == "ORACLE":
        d.update({"statistic": "truth", "n_used": 0, "mean": p, "promote": p >= 0.60})
    d["compliant"] = (d["n_used"] == N and d["statistic"] == "overall_rate" and d["theta"] == THETA_CONTRACT)
    return d


def rate(xs):
    return round(sum(1 for x in xs if x) / len(xs), 6) if xs else 0.0


def nonce(agent, kind, key, value):
    return sha(canon({"agent": agent, "kind": kind, "key": key, "value": value}))[:16]


def pub_of(agent):
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{agent}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


def verify_memory(entries, pubs):
    prev, bad = "", []
    for e in entries:
        e = {**e, "grants_authority": False, "executable": False}
        body = canon({k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                        "nonce", "created_at", "grants_authority", "executable")})
        ok = e["prev"] == prev and e["tenant"] == TENANT
        ok = ok and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"]
        ok = ok and e["nonce"] == nonce(e["agent"], e["kind"], e["key"], e["value"])
        if ok:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(
                    bytes.fromhex(e["sig"]), body)
            except Exception:
                ok = False
        if not ok:
            bad.append(e["seq"])
        prev = e["hash"]
    return bad


def merkle(files):
    l = sorted(sha(p.read_bytes()) for p in files)
    while len(l) > 1:
        if len(l) % 2:
            l.append(l[-1])
        l = [sha((l[i] + l[i + 1]).encode()) for i in range(0, len(l), 2)]
    return l[0] if l else sha(b"")


def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    ck, fail = [], []

    def check(name, ok, detail=""):
        ck.append({"check": name, "ok": bool(ok), "detail": detail})
        if not ok:
            fail.append(name)

    args = json.loads((root / "PRC_RUN_REPORT.json").read_text())
    rows = json.loads((root / "PRC_ROWS.json").read_text())
    mem = json.loads((root / "PRC_MEMORY.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    pre = json.loads((root / "PRC_PREREGISTRATION.json").read_text())
    man = json.loads((root / "MANIFEST.json").read_text())

    for k in ("salt1", "salt2"):
        check(f"salt commitment {k}", sha(salts[k].encode()) == pre["salts_commitment"][k])

    derived = {}
    for s in ("salt1", "salt2"):
        derived[s] = []
        for c in range(CAMPAIGNS):
            xs = draws(salts[s], c)
            p = truth_p(salts[s], c)
            derived[s].append({"campaign": c, "truth_p": p, "real": p >= 0.60,
                               "draws": "".join("1" if x else "0" for x in xs),
                               "arms": {a: decide(xs, a, p) for a in ARMS}})

    mismatch = 0
    index = {(r["salt"], r["campaign"]): r for r in rows}
    for s in derived:
        for w in derived[s]:
            r = index.get((s, w["campaign"]))
            if r is None or r["draws"] != w["draws"] or r["real"] != w["real"]:
                mismatch += 1
                continue
            for a in ARMS:
                got, exp = r["arms"][a], w["arms"][a]
                if any(got[k] != exp[k] for k in ("n_used", "statistic", "theta", "mean",
                                                  "promote", "compliant")):
                    mismatch += 1
    check("every campaign and every analysis re-derives exactly", mismatch == 0, f"{mismatch} mismatches")

    def fp(s, a):
        return rate([w["arms"][a]["promote"] for w in derived[s] if not w["real"]])

    def tr(s, a):
        return rate([w["arms"][a]["promote"] for w in derived[s] if w["real"]])

    h1 = all(fp(s, "CONTRACT") <= 0.10 for s in derived)
    h2 = all(all(fp(s, a) > fp(s, "CONTRACT") for a in ("NONE", "SUBSET", "PEEK")) for s in derived)
    h3 = all(tr(s, "CONTRACT") >= 0.50 for s in derived)
    h4, detail4 = True, {}
    for s in derived:
        bad = good = badf = goodf = 0
        for w in derived[s]:
            for a in ("NONE", "CONTRACT", "SUBSET", "PEEK"):
                d = w["arms"][a]
                if not d["promote"]:
                    continue
                if d["compliant"]:
                    good += 1
                    goodf += 0
                else:
                    bad += 1
                    badf += 1
        detail4[s] = {"noncompliant": bad, "flagged": badf, "compliant": good, "false_flags": goodf}
        h4 = h4 and bad > 0 and badf == bad and goodf == 0
    mm = 0
    for s in derived:
        for a in ARMS:
            rep = args["measurements"][s][a]
            exp = {
                "false_promotion_rate": fp(s, a),
                "true_retention": tr(s, a),
                "promotions": sum(1 for w in derived[s] if w["arms"][a]["promote"]),
                "false_promotions": sum(1 for w in derived[s] if w["arms"][a]["promote"] and not w["real"]),
                "true_promotions": sum(1 for w in derived[s] if w["arms"][a]["promote"] and w["real"]),
                "compliant_promotions": sum(1 for w in derived[s] if w["arms"][a]["promote"] and w["arms"][a]["compliant"]),
            }
            if any(rep.get(k) != v for k, v in exp.items()):
                mm += 1
    check("measurement summary re-derives", mm == 0, f"{mm} mismatches")
    check("H1 contract controls false promotions", h1)
    check("H2 post-hoc liberty inflates errors", h2)
    check("H3 contract keeps real improvements", h3)
    check("H4 compliance detector is exact", h4, json.dumps(detail4))

    # memory
    pubs = {a: pub_of(a) for a in ("contract", "analyst", "verifier")}
    check("published memory keys derive from the seed", pubs == mem["keys"])
    bad_any = []
    for key, entries in mem["entries"].items():
        bad_any += [(key, b) for b in verify_memory(entries, pubs)]
    check("every governed-memory entry verifies", not bad_any, str(bad_any[:5]))
    ok_probe = True
    for s in ("salt1", "salt2"):
        p = args["probes"][s]
        ok_probe = ok_probe and p["chain_and_signatures"] and p["replay_refused"] and p["tamper_detected"] \
                   and p["contract_before_data"] and p["authority_from_memory_refused"] \
                   and p["authority_flag_false_everywhere"]
        cseq = [e["seq"] for e in mem["entries"][s] if e["kind"] == "contract"]
        rseq = [e["seq"] for e in mem["entries"][s] if e["kind"] == "result"]
        check(f"{s} every contract precedes every result", bool(cseq) and bool(rseq) and max(cseq) < min(rseq))
    check("H5 integrity, ordering and no authority", ok_probe)
    check("reported hypothesis verdicts match", {k: v.get("verdict") for k, v in args["hypotheses"].items()}
          == {"H1_contract_controls_false_promotions": "SUPPORTED" if h1 else "NOT_SUPPORTED",
              "H2_post_hoc_liberty_inflates_errors": "SUPPORTED" if h2 else "NOT_SUPPORTED",
              "H3_contract_keeps_real_improvements": "SUPPORTED" if h3 else "NOT_SUPPORTED",
              "H4_compliance_detector_is_exact": "SUPPORTED" if h4 else "NOT_SUPPORTED",
              "H5_integrity_and_contract_ordering": "SUPPORTED" if ok_probe else "NOT_SUPPORTED",
              "H6_external_review": "BLOCKED"})
    check("verdict follows from H1-H5",
          args["verdict"] == ("EXPERIMENT_CONTRACT_SUPPORTED" if (h1 and h2 and h3 and h4 and ok_probe)
                              else "NOT_SUPPORTED"))

    fs = sorted(p for p in root.rglob("*") if p.is_file()
                and "__pycache__" not in p.parts
                and p.name not in ("MANIFEST.json", "PRC_MANIFEST.json", "MERKLE_ROOT.txt",
                                   "PRC_SIGNED_BODY.json", "PRC_VERIFICATION_RESULTS.json",
                                   "PRC_TAMPER_RESULTS.json", "PRC_PUBLIC_CHECK.json", "PUBLICATION.json",
                                   "PRC_OMEGA_SEAL.json", "PRC_PUBKEY.pem"))
    body = {k: man[k] for k in ("schema", "evolution", "status", "name", "created_at", "verifier",
                                "pubkey_ed25519", "files", "merkle_root", "engine_withheld",
                                "external_review")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        check("manifest signature", True)
    except Exception:
        check("manifest signature", False)
    check("file hashes match the manifest",
          all(man["files"].get(str(p.relative_to(root))) == sha(p.read_bytes()) for p in fs))
    check("manifest lists exactly the bundle files",
          sorted(man["files"]) == sorted(str(p.relative_to(root)) for p in fs))
    check("merkle root recomputes", man["merkle_root"] == merkle(fs))
    check("engine source withheld", man.get("engine_withheld") is True and
          not any(p.suffix == ".py" and "verify" not in p.name for p in fs))
    check("no model calls", args.get("model_calls") == 0)
    check("status line", args.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    check("external review not claimed", man.get("external_review") == "NOT_OBTAINED")

    print(json.dumps({"checks": len(ck), "passed": sum(1 for c in ck if c["ok"]), "failed": fail,
                      "verdict": args["verdict"]}, indent=1))
    return 0 if not fail else 1


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