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

Verifies the manifest signature, every 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, both regimes, all five
policies, the detector, the exploration, every world decision, calibration, false alarms and every
hypothesis.

Usage: python3 verify_nfc_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
TESTABLE = 48
BUDGET = 240
CHANGE = 168
K_CELL = 8.0
K_CAND = 4.0
BASE = [0.66, 0.46, 0.26, 0.16]
DEPTH_BONUS = [0.03, 0.00, -0.03]
JITTER = 0.02
ARMS = ["static", "window", "detector", "screen", "oracle"]
AGENTS = ["atlas", "borealis", "cetus", "draco", "mallory"]
WORLDS = 64
CTRL = 32
WINDOW = 80
DETECT_WIN = 16
DETECT_GAP = 0.22
DETECT_CHECKS = 2
TENANT = "cain42-nfc"
SEED = "nfc"
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, t):
    h = sha(canon([salt, world, arm, cand, t]))
    return int(h[:16], 16) / float(16 ** 16)


def world(salt, w, stationary=False):
    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):
                j = rng.uniform(-JITTER, JITTER)
                p0 = min(0.88, max(0.12, BASE[f] + DEPTH_BONUS[d] + j))
                p1 = min(0.88, max(0.12, BASE[(f + 2) % FAMILIES] + DEPTH_BONUS[d] + j))
                if stationary:
                    p1 = p0
                cands.append({"i": i, "family": f, "depth": d + 2, "j": j,
                              "p0": p0, "p1": p1, "heldout": k == 0})
                i += 1
    return cands


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


def p_at(c, t, stationary=False):
    return c["p0"] if (stationary or t < CHANGE) else c["p1"]


def fit(cands, obs, since=0):
    tn = ts = 0
    cells = {}
    for c in cands:
        cells.setdefault(cell_of(c), [0, 0])
    for c in cands:
        v = [s for (t, s) in obs.get(c["i"], []) if t >= since]
        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
    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 = [s for (t, s) in obs.get(c["i"], []) if t >= since]
        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 brier(phat, cands):
    pts = [c for c in cands if c["heldout"]]
    return sum((phat[c["i"]] - c["p1"]) ** 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["p1"] for c in sel) / len(sel))
    return total


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


def campaign(cands, salt, w, arm, stationary=False):
    testable = [c for c in cands if not c["heldout"]]
    obs = {}
    t = 0
    change_at = 0
    alarms = []
    alarmed = False
    mon_set = None
    mon_rate = 0.5
    mon_obs = []
    hits = 0
    replaced = False

    def fit_now():
        since = 0
        if arm == "window":
            since = max(0, t - WINDOW)
        elif arm == "detector":
            since = change_at
        return fit(cands, obs, since)

    def run(c):
        nonlocal t, change_at, alarmed, hits
        p = p_at(c, t, stationary)
        s = 1 if draws(salt, w, arm, c["i"], t) < p else 0
        obs.setdefault(c["i"], []).append((t, s))
        if arm == "detector" and mon_set is not None and c["family"] in mon_set:
            mon_obs.append(s)
            if len(mon_obs) >= DETECT_WIN and len(mon_obs) % 4 == 0:
                recent = sum(mon_obs[-DETECT_WIN:]) / DETECT_WIN
                if mon_rate - recent >= DETECT_GAP:
                    hits += 1
                else:
                    hits = 0
                if not alarmed and hits >= DETECT_CHECKS:
                    alarmed = True
                    alarms.append(t)
                    change_at = t + 1
        t += 1

    def rank(top, k):
        if arm == "screen":
            emp = empirical(obs)
            return sorted(top, key=lambda c: (-emp.get(c["i"], 0.0), c["i"]))[:k]
        phat, _ = fit_now()
        return sorted(top, key=lambda c: (-phat[c["i"]], c["i"]))[:k]

    if arm == "oracle":
        best = max(testable, key=lambda c: (c["p1"], -c["i"]))
        phat, ns = fit(cands, {})
        return {"runs": 0, "promoted": best["i"], "promoted_p": best["p1"],
                "best_p": max(c["p1"] for c in testable), "brier": brier(phat, cands),
                "ece": ece(phat, cands), "detected": False, "latency": None, "alarms": 0,
                "promoted_prechange": 0}

    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)
    if arm == "detector":
        fams = [c["family"] for c in top6]
        mon_set = {max(set(fams), key=fams.count)}
        vals = [s for c in testable if c["family"] in mon_set
                for (tt, s) in obs.get(c["i"], []) if tt < 156]
        mon_rate = (sum(vals) / len(vals)) if vals else 0.5
    while t < BUDGET:
        if arm == "detector" and alarmed and not replaced:
            for c in testable:
                if t >= BUDGET:
                    break
                run(c)
            top6 = rank(testable, 6)
            replaced = True
            continue
        for c in top6:
            if t >= BUDGET:
                break
            run(c)

    phat, ns = fit_now()
    if arm == "screen":
        emp = empirical(obs)
        elig = [c for c in testable if len(obs.get(c["i"], [])) >= 8]
        promoted = max(elig, key=lambda c: (emp[c["i"]], -c["i"]))
    elif arm == "detector" and replaced:
        elig = [c for c in testable if len(obs.get(c["i"], [])) >= 3] or testable
        promoted = max(elig, key=lambda c: (phat[c["i"]], -c["i"]))
    else:
        elig = [c for c in testable if len(obs.get(c["i"], [])) >= 8] or \
               [c for c in testable if len(obs.get(c["i"], [])) >= 2] or testable
        promoted = max(elig, key=lambda c: (phat[c["i"]], -c["i"]))
    lat = [a - CHANGE + 1 for a in alarms if a >= CHANGE]
    return {"runs": t, "promoted": promoted["i"], "promoted_p": promoted["p1"],
            "best_p": max(c["p1"] for c in testable), "brier": brier(phat, cands),
            "ece": ece(phat, cands), "detected": bool(lat),
            "latency": min(lat) if lat else None, "alarms": len(alarms),
            "promoted_prechange": int(promoted["p0"] - promoted["p1"] > 0.10)}


def summarize(rows):
    n = len(rows)
    lats = [r["latency"] for r in rows if r["latency"] is not None]
    return {
        "regret_mean": mean([r["best_p"] - r["promoted_p"] for r in rows]),
        "promoted_p_mean": mean([r["promoted_p"] for r in rows]),
        "brier_mean": mean([r["brier"] for r in rows]),
        "ece_mean": mean([r["ece"] for r in rows]),
        "detected_rate": sum(1 for r in rows if r["detected"]) / n,
        "latency_median": statistics.median(lats) if lats else None,
        "latency_mean": mean(lats),
        "alarms_mean": mean([r["alarms"] for r in rows]),
        "promoted_prechange_rate": mean([r["promoted_prechange"] for r in rows]),
        "runs_mean": mean([r["runs"] for r in rows]),
        "runs_max": max(r["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 / "NFC_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 / "NFC_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 declaration")
    worlds = int(rep["design"]["worlds_per_salt"])
    controls = int(rep["design"]["controls_per_salt"])

    pubs = {a: pubhex(a) for a in AGENTS}
    exp = {}
    for key in ("salt1", "salt2"):
        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", "detected", "latency", "alarms", "promoted_prechange"):
                    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"):
                    if abs(got[f] - want[f]) > 1e-9:
                        fail(f"{key} w{w} {arm} {f}")
        for arm in ARMS:
            agg = summarize(got_worlds[arm])
            for f, v in agg.items():
                rv = rep["scenarios"][key]["arms"][arm][f]
                if isinstance(v, float):
                    if rv is None or abs(v - rv) > 1e-9:
                        fail(f"{key} agg {arm} {f}")
                elif v != rv:
                    fail(f"{key} agg {arm} {f}")
        ctrl = [campaign(world(salt, w, stationary=True), salt, 1000 + w,
                         "detector", stationary=True) for w in range(controls)]
        fa = sum(1 for c in ctrl if c["alarms"] > 0) / controls
        if abs(fa - rep["scenarios"][key]["controls"]["false_alarm_rate"]) > 1e-9:
            fail(f"{key} false alarms")
        for c, want in zip(ctrl, rep["scenarios"][key]["controls"]["worlds"]):
            if c["alarms"] != want["alarms"]:
                fail(f"{key} control alarms")

        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 in export")
        if mem["tenant_visible"] != 0 or not mem["tamper_detected"] or not mem["authority_refused"]:
            fail(f"{key} probes")
        if mem["distinct_pids"] != 4:
            fail(f"{key} four-process drill")
        obs = {}
        change_at = 0
        for e in ents:
            if e["kind"] == "experiment":
                obs.setdefault(e["value"]["candidate"], []).append(
                    (e["value"]["t"], e["value"]["success"]))
            elif e["kind"] == "alarm":
                change_at = e["value"]["since"]
        phat, ns = fit(world(salt, mem["world"]), obs, change_at)
        need = 3 if change_at else 8
        elig = [c for c in world(salt, mem["world"])
                if not c["heldout"] and len(obs.get(c["i"], [])) >= need]
        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")

        a = rep["scenarios"][key]["arms"]
        fa = rep["scenarios"][key]["controls"]["false_alarm_rate"]
        exp[key] = {
            "H1_detection": a["detector"]["detected_rate"] >= 0.90
            and (a["detector"]["latency_median"] or 999) <= 24 and fa <= 0.30,
            "H2_recovery": a["detector"]["regret_mean"] <= 0.10
            and a["detector"]["regret_mean"] <= a["static"]["regret_mean"] - 0.10,
            "H3_recalibration": a["detector"]["brier_mean"] <= 0.045
            and a["detector"]["brier_mean"] <= a["static"]["brier_mean"] - 0.02,
            "H4_the_trap": a["static"]["promoted_prechange_rate"] >= 0.80
            and a["static"]["regret_mean"] >= 0.15,
            "H5_budget": max(v["runs_max"] for v in a.values()) <= BUDGET,
            "H6_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_detection", "H2_recovery", "H3_recalibration", "H4_the_trap",
              "H5_budget", "H6_governance"):
        ok = all(exp[key][k] for key in ("salt1", "salt2"))
        want = "SUPPORTED" if ok else "NOT_SUPPORTED"
        got = rep["hypotheses"][k]["verdict"]
        if got != want:
            fail(f"pooled {k}: reported {got}, recomputed {want}")
    if rep["hypotheses"]["H7_external_review"]["verdict"] != "BLOCKED":
        fail("H7")

    want_v = ("NONSTATIONARY_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(f"verdict: reported {rep['verdict']}, recomputed {want_v}")

    rows = sum(len(rep["scenarios"][k]["worlds"][a]) for k in ("salt1", "salt2") for a in ARMS)
    print(f"OK: NFC verified — 2 salts, {rows} arm-world rows and 2x{controls} stationary controls "
          f"re-derived, {len(rep['scenarios']['salt1']['memory']['entries'])} memory entries checked")
    return 0


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