#!/usr/bin/env python3
"""CFI standalone auditor. Imports no CAIN code; runs from a clean copy of the bundle."""
from __future__ import annotations
import hashlib, json, random, statistics, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

FAMILIES, DEPTHS, PER_CELL = 4, 3, 5
CANDIDATES, TESTABLE, HELDOUT, CALIB, PROMOTION, BUDGET = 60, 48, 12, 12, 36, 240
K_CELL, K_CAND = 8.0, 4.0
BASE = [0.60, 0.48, 0.36, 0.24]
DEPTH_BONUS = [0.04, 0.00, -0.04]
JITTER = 0.03
NORMAL_HALF = 0.08
BAR = 0.40
ARMS = ["point", "normal", "conformal90", "conformal80", "oracle"]
AGENTS = ["atlas", "borealis", "cetus", "draco", "mallory"]
WORLDS = 32
TENANT, SEED = "cain42-cfi", "cfi"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"

def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def mean(xs): return statistics.mean(xs) if xs else 0.0

def draws(salt, world, cand, run_no):
    h = sha(canon([salt, world, cand, run_no])); return int(h[:16], 16) / float(16 ** 16)

def world(salt, w):
    rng = random.Random(int(sha(canon([salt, w, "world"]))[:16], 16))
    cands = []; i = 0
    for f in range(FAMILIES):
        for d in range(DEPTHS):
            for k in range(PER_CELL):
                p = min(0.88, max(0.12, BASE[f] + DEPTH_BONUS[d] + rng.uniform(-JITTER, JITTER)))
                role = "test" if k == 0 else ("calib" if k == 1 else "promote")
                cands.append({"i": i, "family": f, "depth": d + 2, "p": p, "role": role}); i += 1
    return cands

def cell_of(c): return c["family"] * DEPTHS + c["depth"] - 2

def fit(cands, obs, only_role=None):
    by = {c["i"]: c for c in cands}
    tn = ts = 0
    cells = {}
    for c in cands: cells.setdefault(cell_of(c), [0, 0])
    for i, v in obs.items():
        c = by[i]
        if only_role and c["role"] != only_role: continue
        tn += len(v); ts += sum(v); cells[cell_of(c)][0] += sum(v); cells[cell_of(c)][1] += len(v)
    glob = (ts / tn) if tn else 0.5
    ch = {k: ((s + K_CELL * glob) / (n + K_CELL) if (n + K_CELL) else glob) for k, (s, n) in cells.items()}
    phat, ns = {}, {}
    for c in cands:
        v = obs.get(c["i"], []) if (only_role is None or c["role"] == only_role) else []
        n = len(v); h = ch[cell_of(c)]
        phat[c["i"]] = (sum(v) + K_CAND * h) / (n + K_CAND) if (n + K_CAND) else h; ns[c["i"]] = n
    return phat, ns

def q_conf(cands, phat, coverage):
    res = sorted(abs(c["p"] - phat[c["i"]]) for c in cands if c["role"] == "calib")
    n = len(res); k = min(max(int(-(-((n + 1) * coverage) // 1)), 1), n)
    return res[k - 1]

def coverage(phat, cands, half):
    pts = [c for c in cands if c["role"] == "test"]
    return sum(1 for c in pts if abs(phat[c["i"]] - c["p"]) <= half) / len(pts)

def campaign(cands, salt, w, arm):
    testable = [c for c in cands if c["role"] != "test"]
    promotion = [c for c in cands if c["role"] == "promote"]
    obs = {}; runs = 0
    def run(c):
        nonlocal runs
        n = len(obs.setdefault(c["i"], []))
        obs[c["i"]].append(1 if draws(salt, w, c["i"], n) < c["p"] else 0); runs += 1
    for _ in range(2):
        for c in testable: run(c)
    for _ in range(4):
        for c in promotion: run(c)
    phat, ns = fit(cands, obs, only_role="promote")
    q90, q80 = q_conf(cands, phat, 0.90), q_conf(cands, phat, 0.80)
    cc, cn = coverage(phat, cands, q90), coverage(phat, cands, NORMAL_HALF)
    if arm == "oracle":
        best = max(promotion, key=lambda c: (c["p"], -c["i"]))
        return {"runs": 0, "promoted": best["i"], "promoted_p": best["p"],
                "best_p": max(c["p"] for c in promotion), "abstained": False,
                "q90": q90, "q80": q80, "cov_conf": cc, "cov_norm": cn, "width": 2 * q90}
    def pick(half):
        elig = [c for c in promotion if phat[c["i"]] - half >= BAR]
        return (max(elig, key=lambda c: (phat[c["i"]], -c["i"])), False) if elig else (None, True)
    if arm == "point":
        promoted, abstained = max(promotion, key=lambda c: (phat[c["i"]], -c["i"])), False
    elif arm == "normal":
        promoted, abstained = pick(NORMAL_HALF)
    elif arm == "conformal90":
        promoted, abstained = pick(q90)
    else:
        promoted, abstained = pick(q80)
    return {"runs": runs, "promoted": promoted["i"] if promoted else -1,
            "promoted_p": promoted["p"] if promoted else None,
            "best_p": max(c["p"] for c in promotion), "abstained": abstained,
            "q90": q90, "q80": q80, "cov_conf": cc, "cov_norm": cn, "width": 2 * q90}

def summarize(rows):
    n = len(rows); ok = [r for r in rows if r["promoted"] >= 0]
    return {"regret_mean": mean([r["best_p"] - r["promoted_p"] for r in ok]) if ok else None,
            "promoted_p_mean": mean([r["promoted_p"] for r in ok]) if ok else None,
            "abstain_rate": sum(1 for r in rows if r["abstained"]) / n,
            "coverage_conformal": mean([r["cov_conf"] for r in rows]),
            "coverage_normal": mean([r["cov_norm"] for r in rows]),
            "q90_mean": mean([r["q90"] for r in rows]), "q80_mean": mean([r["q80"] for r in rows]),
            "width_mean": mean([r["width"] for r in rows]),
            "runs_mean": mean([r["runs"] for r in rows]), "runs_max": max(r["runs"] for r in rows)}

def keypair(a): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
def pubhex(a): return keypair(a).public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()

def verify_entries(entries, pubs):
    prev = ""; bad = []
    for e in entries:
        payload = {k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev", "created_at", "grants_authority", "executable")}
        body = canon(payload)
        ok = (e["prev"] == prev and e["tenant"] == TENANT and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"])
        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 fail(m): print("FAIL:", m); sys.exit(1)

def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    man = json.loads((root / "CFI_MANIFEST.json").read_text())
    if man.get("status") != STATUS: fail("status")
    if man.get("external_review") != "NOT_OBTAINED": fail("external review")
    body = {k: v for k, v in man.items() if k != "signature"}
    try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
    except Exception: fail("manifest signature")
    for n, h in man["files"].items():
        p = root / n
        if not p.exists() or sha(p.read_bytes()) != h: fail(f"file {n}")
    if merkle([root / n for n in man["files"]]) != man["merkle_root"]: fail("merkle")
    rep = json.loads((root / "CFI_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    for k in ("salt1", "salt2"):
        if sha(salts[k].encode()) != rep["salt_commitment"][k]: fail(f"salt {k}")
    if rep["design"]["model_calls"] != 0: fail("model")
    worlds = int(rep["design"]["worlds_per_salt"])
    pubs = {a: pubhex(a) for a in AGENTS}
    exp = {}
    for key in ("salt1", "salt2"):
        salt = salts[key]
        got = {a: [] for a in ARMS}
        for w in range(worlds):
            cands = world(salt, w)
            for a in ARMS:
                r = campaign(cands, salt, w, a); got[a].append(r)
                want = rep["scenarios"][key]["worlds"][a][w]
                for f in ("runs", "promoted", "abstained"):
                    if r[f] != want[f]: fail(f"{key} w{w} {a} {f}")
                for f in ("promoted_p", "best_p", "q90", "q80", "cov_conf", "cov_norm", "width"):
                    if (r[f] is None) != (want[f] is None) or (r[f] is not None and abs(r[f] - want[f]) > 1e-9):
                        fail(f"{key} w{w} {a} {f}")
        for a in ARMS:
            agg = summarize(got[a])
            for f, v in agg.items():
                rv = rep["scenarios"][key]["arms"][a][f]
                if isinstance(v, float):
                    if rv is None or abs(v - rv) > 1e-9: fail(f"{key} agg {a} {f}")
                elif v != rv: fail(f"{key} agg {a} {f}")
        mem = rep["scenarios"][key]["memory"]; ents = mem["entries"]
        if verify_entries(ents, pubs): fail(f"{key} chain")
        if any(e["tenant"] != TENANT or e["grants_authority"] is not False for e in ents): fail(f"{key} tenant/authority")
        if mem["tenant_visible"] != 0 or not mem["tamper_detected"] or not mem["authority_refused"]: fail(f"{key} probe")
        if mem["distinct_pids"] != 4: fail(f"{key} pids")
        obs = {}
        for e in ents:
            if e["kind"] == "experiment": obs.setdefault(e["value"]["candidate"], []).append(e["value"]["success"])
        phat, ns = fit(world(salt, mem["world"]), obs, only_role="promote")
        q = q_conf(world(salt, mem["world"]), phat, 0.90)
        elig = [c for c in world(salt, mem["world"]) if c["role"] == "promote" and phat[c["i"]] - q >= BAR]
        replay = max(elig, key=lambda c: (phat[c["i"]], -c["i"]))["i"] if elig else -1
        if replay != mem["live_promoted"] or not mem["replay_equal"]: fail(f"{key} replay")
        a = rep["scenarios"][key]["arms"]
        exp[key] = {
            "H1_coverage": a["conformal90"]["coverage_conformal"] >= 0.80 and a["conformal90"]["coverage_conformal"] >= a["normal"]["coverage_normal"] + 0.10,
            "H2_sharpness": a["conformal90"]["width_mean"] <= 0.45,
            "H3_gate": a["conformal90"]["promoted_p_mean"] >= a["point"]["promoted_p_mean"] - 0.02 and a["conformal90"]["abstain_rate"] <= 0.30,
            "H4_budget": max(v["runs_max"] for v in a.values()) <= BUDGET,
            "H5_governance": not mem["chain_bad"] and mem["replay_equal"] and mem["tenant_visible"] == 0 and mem["tamper_detected"] and mem["authority_refused"] and mem["distinct_pids"] == 4,
        }
    for k in ("H1_coverage", "H2_sharpness", "H3_gate", "H4_budget", "H5_governance"):
        ok = all(exp[key][k] for key in ("salt1", "salt2"))
        want = "SUPPORTED" if ok else "NOT_SUPPORTED"
        if rep["hypotheses"][k]["verdict"] != want: fail(f"{k}")
    if rep["hypotheses"]["H6_external_review"]["verdict"] != "BLOCKED": fail("H6")
    want_v = "CONFORMAL_FORECAST_SUPPORTED" if all(rep["hypotheses"][k]["verdict"] in ("SUPPORTED", "BLOCKED") for k in rep["hypotheses"]) else "NOT_SUPPORTED"
    if rep["verdict"] != want_v: fail("verdict")
    rows = sum(len(rep["scenarios"][k]["worlds"][a]) for k in ("salt1", "salt2") for a in ARMS)
    print(f"OK: CFI verified — 2 salts, {rows} arm-world rows re-derived, {len(rep['scenarios']['salt1']['memory']['entries'])} memory entries checked")
    return 0

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