#!/usr/bin/env python3
"""CFS standalone auditor. Imports no CAIN code; runs from a clean copy of the bundle.

Verifies the manifest signature, every declared file hash and the Merkle root, the salt commitment,
every signed governed-memory entry (chain, signature, replay, tenant, tamper, no authority), and
**re-derives the whole campaign from the revealed salts**: the 60 candidates, the held-out set, all
eight policies, every per-world decision, the calibration, and every hypothesis.

Usage: python3 verify_cfs_offline.py [bundle_dir]
"""
from __future__ import annotations

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

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

FAMILIES = 4
DEPTHS = 3
PER_CELL = 5
CANDIDATES = 60
BUDGET = 240
K_CELL = 8.0
K_CAND = 4.0
BASE = [0.58, 0.48, 0.38, 0.28]
DEPTH_BONUS = [0.04, 0.00, -0.04]
JITTER = 0.02
ARMS = ["uniform", "screen", "forecast", "selective", "ucb", "oracle",
        "poison_trust", "poison_verified"]
AGENTS = ["atlas", "borealis", "cetus", "draco", "mallory"]
WORLDS = 64
FORGED = 12
VERIFY = 24
POISON_N = 8
TENANT = "cain42-cfs"
SEED = "cfs"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"


def sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def canon(o) -> bytes:
    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, arm, cand, run_no):
    h = sha(canon([salt, world, arm, 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 = BASE[f] + DEPTH_BONUS[d] + rng.uniform(-JITTER, JITTER)
                p = min(0.88, max(0.12, p))
                cands.append({"i": i, "family": f, "depth": d + 2, "p": p, "heldout": k == 0})
                i += 1
    return cands


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


def fit(cands, obs):
    total_n = sum(len(v) for v in obs.values())
    total_s = sum(sum(v) for v in obs.values())
    glob = (total_s / total_n) if total_n else 0.5
    cells = {}
    for c in cands:
        cells.setdefault(cell_of(c), [0, 0])
    for c in cands:
        v = obs.get(c["i"], [])
        cells[cell_of(c)][0] += sum(v)
        cells[cell_of(c)][1] += len(v)
    cell_hat = {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"], [])
        n = len(v)
        cell = cell_hat[cell_of(c)]
        phat[c["i"]] = (sum(v) + K_CAND * cell) / (n + K_CAND) if (n + K_CAND) else cell
        ns[c["i"]] = n
    return phat, ns


def lcb(phat, n):
    se = (phat * (1 - phat) / (n + K_CAND)) ** 0.5
    return phat - 1.2816 * se


def brier(phat, cands):
    pts = [c for c in cands if c["heldout"]]
    return sum((phat[c["i"]] - c["p"]) ** 2 for c in pts) / len(pts)


def ece(phat, cands, bins=4):
    pts = [c for c in cands if c["heldout"]]
    edges = [i / bins for i in range(bins + 1)]
    total = 0.0
    for b in range(bins):
        lo, hi = edges[b], edges[b + 1]
        sel = [c for c in pts if lo <= phat[c["i"]] < hi or (b == bins - 1 and phat[c["i"]] == hi)]
        if not sel:
            continue
        total += (len(sel) / len(pts)) * abs(sum(phat[c["i"]] for c in sel) / len(sel)
                                              - sum(c["p"] for c in sel) / len(sel))
    return total


def empirical(obs):
    return {i: (sum(v) / len(v) if v else 0.0) for i, v in obs.items()}


def campaign(cands, salt, w, arm):
    testable = [c for c in cands if not c["heldout"]]
    obs = {}
    runs = 0
    forged = []
    verify_runs = 0
    rejected = 0
    abstained = False

    def run(c):
        nonlocal runs
        n = len(obs.setdefault(c["i"], []))
        obs[c["i"]].append(1 if draws(salt, w, arm, c["i"], n) < c["p"] else 0)
        runs += 1

    def rank(top, k):
        if arm in ("forecast", "selective", "poison_trust", "poison_verified"):
            phat, _ = fit(cands, obs)
            return sorted(top, key=lambda c: (-phat[c["i"]], c["i"]))[:k]
        emp = empirical(obs)
        return sorted(top, key=lambda c: (-emp.get(c["i"], 0.0), c["i"]))[:k]

    if arm == "oracle":
        best = max(testable, key=lambda c: (c["p"], -c["i"]))
        phat, ns = fit(cands, {})
        return {"runs": 0, "promoted": best["i"], "promoted_p": best["p"],
                "best_p": max(c["p"] for c in testable), "abstained": False,
                "brier": brier(phat, cands), "ece": ece(phat, cands),
                "forged": 0, "forgeries_rejected": 0, "poison_promoted": 0, "verify_runs": 0}
    if arm == "ucb":
        for c in testable:
            run(c)
        while runs < BUDGET:
            tot = sum(len(v) for v in obs.values())
            best, bk = None, -1e9
            for c in testable:
                n = len(obs[c["i"]])
                k = sum(obs[c["i"]]) / n + (2.0 * (tot and __import__("math").log(tot)) / n) ** 0.5
                if k > bk:
                    bk, best = k, c
            run(best)
        emp = empirical(obs)
        elig = [c for c in testable if len(obs[c["i"]]) >= 4]
        promoted = max(elig, key=lambda c: (emp[c["i"]], -c["i"]))
        phat, ns = fit(cands, obs)
    elif arm == "uniform":
        for _ in range(5):
            for c in testable:
                run(c)
        emp = empirical(obs)
        promoted = max(testable, key=lambda c: (emp[c["i"]], -c["i"]))
        phat, ns = fit(cands, obs)
    else:
        for _ in range(2):
            for c in testable:
                run(c)
        top20 = rank(testable, 20)
        for _ in range(3):
            for c in top20:
                run(c)
        top6 = rank(testable, 6)
        for _ in range(14):
            for c in top6:
                run(c)
        phat, ns = fit(cands, obs)
        if arm in ("poison_trust", "poison_verified"):
            forged = [c["i"] for c in sorted(testable, key=lambda c: (c["p"], c["i"]))[:POISON_N]]
            if arm == "poison_trust":
                for i in forged:
                    obs[i] = obs.get(i, []) + [1] * FORGED
                phat, ns = fit(cands, obs)
            else:
                for i in forged:
                    c = next(x for x in testable if x["i"] == i)
                    obs_v = [1 if draws(salt, w, "verify", i, r) < c["p"] else 0
                             for r in range(VERIFY)]
                    verify_runs += VERIFY
                    if 1.0 - sum(obs_v) / VERIFY > 0.25:
                        rejected += FORGED
                    else:
                        obs[i] = obs.get(i, []) + obs_v
                phat, ns = fit(cands, obs)
        if arm == "selective":
            emp_sel = empirical(obs)
            elig = [c for c in testable if ns[c["i"]] >= 8]
            best = max(elig, key=lambda c: (emp_sel[c["i"]], -c["i"]))
            if lcb(phat[best["i"]], ns[best["i"]]) < 0.45:
                promoted, abstained = None, True
            else:
                promoted, abstained = best, False
        else:
            elig = [c for c in testable if ns[c["i"]] >= 8]
            promoted = max(elig, key=lambda c: (phat[c["i"]], -c["i"]))
    if arm == "screen":
        emp = empirical(obs)
        elig = [c for c in testable if len(obs[c["i"]]) >= 8]
        promoted = max(elig, key=lambda c: (emp[c["i"]], -c["i"]))
    best_p = max(c["p"] for c in testable)
    return {"runs": runs, "promoted": promoted["i"] if promoted else -1,
            "promoted_p": promoted["p"] if promoted else None, "best_p": best_p,
            "abstained": bool(abstained), "brier": brier(phat, cands), "ece": ece(phat, cands),
            "forged": FORGED * len(forged), "forgeries_rejected": rejected,
            "poison_promoted": int(bool(promoted) and promoted["i"] in forged),
            "verify_runs": verify_runs}


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,
        "hit_best_rate": sum(1 for r in rows if r["promoted"] >= 0
                             and r["promoted_p"] == r["best_p"]) / n,
        "near_best_rate": sum(1 for r in rows if r["promoted"] >= 0
                              and (r["best_p"] - r["promoted_p"]) <= 0.02) / n,
        "false_promotion_rate": sum(1 for r in rows if r["promoted"] >= 0
                                    and r["promoted_p"] < 0.55 and r["best_p"] >= 0.65) / n,
        "abstain_rate": sum(1 for r in rows if r["abstained"]) / n,
        "brier_mean": mean([r["brier"] for r in rows]),
        "ece_mean": mean([r["ece"] for r in rows]),
        "runs_mean": mean([r["runs"] for r in rows]),
        "runs_max": max(r["runs"] for r in rows),
        "poison_promoted_rate": sum(r["poison_promoted"] for r in rows) / n,
        "forgeries": sum(r["forged"] for r in rows),
        "forgeries_rejected": sum(r["forgeries_rejected"] for r in rows),
        "verify_runs": sum(r["verify_runs"] for r in rows),
    }


def keypair(agent):
    return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{agent}".encode()).digest())


def pubhex(agent):
    return keypair(agent).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(msg):
    print("FAIL:", msg)
    sys.exit(1)


def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    man = json.loads((root / "CFS_MANIFEST.json").read_text())
    if man.get("status") != STATUS:
        fail("status line")
    if man.get("external_review") != "NOT_OBTAINED":
        fail("external review overclaim")
    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 hash {n}")
    if merkle([root / n for n in man["files"]]) != man["merkle_root"]:
        fail("merkle root")

    rep = json.loads((root / "CFS_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    if rep["status"] != STATUS:
        fail("report status")
    for k in ("salt1", "salt2"):
        if sha(salts[k].encode()) != rep["salt_commitment"][k]:
            fail(f"salt commitment {k}")
    if rep["design"]["model_calls"] != 0 or rep["design"]["api_spend_usd"] != 0.0:
        fail("model-call declaration")

    pubs = {a: pubhex(a) for a in AGENTS}
    for key, si in (("salt1", 1), ("salt2", 2)):
        salt = salts[key]
        got_worlds = {a: [] for a in ARMS}
        for w in range(WORLDS):
            cands = world(salt, w)
            for arm in ARMS:
                got = campaign(cands, salt, w, arm)
                got_worlds[arm].append(got)
                want = rep["scenarios"][key]["worlds"][arm][w]
                for f in ("runs", "promoted", "abstained", "poison_promoted"):
                    if got[f] != want[f]:
                        fail(f"{key} w{w} {arm} {f}: {got[f]} != {want[f]}")
                for f in ("promoted_p", "best_p", "brier", "ece"):
                    a, b = got[f], want[f]
                    if (a is None) != (b is None) or (a is not None and abs(a - b) > 1e-9):
                        fail(f"{key} w{w} {arm} {f}")
                for f in ("forged", "forgeries_rejected", "verify_runs"):
                    if got[f] != want[f]:
                        fail(f"{key} w{w} {arm} {f}")
        agg = {a: summarize(got_worlds[a]) for a in ARMS}
        for a in ARMS:
            for f, v in agg[a].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}: {v} != {rv}")
                elif v != rv:
                    fail(f"{key} agg {a} {f}: {v} != {rv}")

        mem = rep["scenarios"][key]["memory"]
        ents = mem["entries"]
        if verify_entries(ents, pubs):
            fail(f"{key} memory chain/signature")
        if any(e["grants_authority"] is not False or e["executable"] is not False for e in ents):
            fail(f"{key} authority in memory")
        if any(e["tenant"] != TENANT for e in ents):
            fail(f"{key} tenant leak in exported memory")
        if mem["tenant_visible"] != 0:
            fail(f"{key} tenant probe")
        if not mem["tamper_detected"]:
            fail(f"{key} tamper probe")
        if not mem["authority_refused"]:
            fail(f"{key} authority probe")
        if mem["distinct_pids"] != 4:
            fail(f"{key} four-process drill")
        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)
        elig = [c for c in world(salt, mem["world"]) if not c["heldout"] and ns[c["i"]] >= 8]
        replay = max(elig, key=lambda c: (phat[c["i"]], -c["i"]))["i"]
        if replay != mem["live_promoted"] or not mem["replay_equal"]:
            fail(f"{key} replay")

        s1 = rep["scenarios"][key]["arms"]
        if s1["forecast"]["brier_mean"] > 0.020 or s1["forecast"]["ece_mean"] > 0.06:
            fail(f"{key} H1")
        if s1["forecast"]["regret_mean"] > s1["screen"]["regret_mean"] + 0.02:
            fail(f"{key} H2 regret")
        if s1["forecast"]["near_best_rate"] < s1["screen"]["near_best_rate"] - 0.15:
            fail(f"{key} H2 near-best")
        if s1["selective"]["abstain_rate"] > 0.25:
            fail(f"{key} H3 abstain")
        if s1["selective"]["regret_mean"] > s1["screen"]["regret_mean"] + 0.02:
            fail(f"{key} H3 regret")
        if s1["poison_trust"]["regret_mean"] < 0.15:
            fail(f"{key} H4 trust regret")
        if s1["poison_trust"]["poison_promoted_rate"] < 0.90:
            fail(f"{key} H4 poison promoted")
        if s1["poison_verified"]["regret_mean"] > s1["forecast"]["regret_mean"] + 0.01:
            fail(f"{key} H4 verified regret")
        if s1["poison_verified"]["poison_promoted_rate"] != 0:
            fail(f"{key} H4 verified poison")
        if s1["poison_verified"]["forgeries_rejected"] < 0.95 * s1["poison_verified"]["forgeries"]:
            fail(f"{key} H4 rejected")
        if max(v["runs_max"] for v in s1.values()) > BUDGET or s1["uniform"]["runs_mean"] != BUDGET:
            fail(f"{key} H5")
    if rep["verdict"] != "CALIBRATED_FORECAST_SUPPORTED":
        fail("verdict")

    rows = 0
    for key in ("salt1", "salt2"):
        for a in ARMS:
            rows += len(rep["scenarios"][key]["worlds"][a])
    print(f"OK: CFS verified — 2 salts, {rows} arm-world rows re-derived, "
          f"{len(rep['scenarios']['salt1']['memory']['entries'])} memory entries checked")
    return 0


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