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

Verifies the manifest and every file, the preregistration hash and salt commitment, every signed
memory entry (Ed25519 + SHA-256 chain), and then **re-derives the whole campaign from the revealed
salts**: the tables, all seven policies, every per-world reward, per-family reward, act count and
catastrophe count, every aggregate, every hypothesis and the verdict.

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

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

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

FAMILIES = 4
AGENTS = 5
MISSIONS = 5
PER_FAMILY_MISSION = 20
TASKS_PER_FAMILY = MISSIONS * PER_FAMILY_MISSION
FALLBACK = 0.55
FAIL = [0.0, 0.0, 0.0, -1.5]
WARMUP = 3
Z_LB = 1.2815515655446004
T_ACT = 0.55
T_TIMID = 0.75
POLICIES = ["oracle", "calibrated", "mean", "always_act", "timid", "ucb", "never_act"]
DESIGNATED = [0, 1, 2, 3]
WORLDS = 40
BASE = [
    [0.93, 0.70, 0.66, 0.60, 0.55],
    [0.62, 0.74, 0.58, 0.52, 0.48],
    [0.59, 0.57, 0.68, 0.53, 0.50],
    [0.40, 0.38, 0.35, 0.43, 0.32],
]
TENANT = "cain42-e463s"
SEED = "e463s"
MEM_AGENTS = ["atlas", "borealis", "cetus", "draco", "eris", "mallory"]
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"

CH = {"n": 0, "ok": 0, "fail": []}


def check(cond, name):
    CH["n"] += 1
    if cond:
        CH["ok"] += 1
    else:
        CH["fail"].append(name)
    return bool(cond)


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 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 build_table(salt, world):
    r = random.Random(int(sha(canon([salt, world, "table"]))[:16], 16))
    return [[[1 if r.random() < BASE[f][a] else 0 for _ in range(TASKS_PER_FAMILY)]
             for a in range(AGENTS)] for f in range(FAMILIES)]


def wilson_lb(successes, n, z=Z_LB):
    if n == 0:
        return 0.0
    p = successes / n
    d = 1 + z * z / n
    centre = p + z * z / (2 * n)
    half = z * math.sqrt(max(0.0, p * (1 - p) / n + z * z / (4 * n * n)))
    return (centre - half) / d


def choose(policy, f, obs):
    if policy == "oracle":
        best = max(range(AGENTS), key=lambda a: (BASE[f][a], -a))
        return best, BASE[f][best] > T_ACT
    if policy == "never_act":
        return 0, False
    if any(obs[(f, a)][1] < WARMUP for a in range(AGENTS)):
        a = min(range(AGENTS), key=lambda a: (obs[(f, a)][1], a))
        return a, policy in ("always_act", "ucb")
    if policy == "ucb":
        total = sum(obs[(f, a)][1] for a in range(AGENTS))

        def u(a):
            s, n = obs[(f, a)]
            return 9.0 if n == 0 else s / n + math.sqrt(2 * math.log(max(2, total)) / n)
        return max(range(AGENTS), key=lambda a: (u(a), -a)), True
    means = {a: obs[(f, a)][0] / obs[(f, a)][1] for a in range(AGENTS)}
    a = DESIGNATED[f]
    if policy == "always_act":
        return a, True
    if policy == "mean":
        return a, means[a] > T_ACT
    lb = wilson_lb(obs[(f, a)][0], obs[(f, a)][1])
    if policy == "calibrated":
        return a, lb > T_ACT
    if policy == "timid":
        return a, lb > T_TIMID
    raise ValueError(policy)


def run_arm(policy, table):
    obs = {(f, a): [0, 0] for f in range(FAMILIES) for a in range(AGENTS)}
    reward, catastrophes = 0.0, 0
    acts = {f: 0 for f in range(FAMILIES)}
    counts = {f: 0 for f in range(FAMILIES)}
    per_family = {f: 0.0 for f in range(FAMILIES)}
    for m in range(MISSIONS):
        for f in range(FAMILIES):
            for i in range(PER_FAMILY_MISSION):
                k = m * PER_FAMILY_MISSION + i
                a, act = choose(policy, f, obs)
                ok = table[f][a][k]
                if act:
                    r = 1.0 if ok else FAIL[f]
                    acts[f] += 1
                    if r < 0:
                        catastrophes += 1
                else:
                    r = FALLBACK
                counts[f] += 1
                reward += r
                per_family[f] += r
                obs[(f, a)][0] += ok
                obs[(f, a)][1] += 1
    return {"reward": reward, "per_family": per_family, "acts": acts, "counts": counts,
            "catastrophes": catastrophes}


def agg_of(worlds):
    out = {}
    for p in POLICIES:
        rs = [w["arms"][p]["reward"] for w in worlds]
        out[p] = {
            "reward_mean": sum(rs) / len(rs),
            "per_family_mean": {f: sum(w["arms"][p]["per_family"][f] for w in worlds) / len(worlds)
                                for f in range(FAMILIES)},
            "act_rate": {f: sum(w["arms"][p]["acts"][f] for w in worlds) /
                         max(1, sum(w["arms"][p]["counts"][f] for w in worlds)) for f in range(FAMILIES)},
            "catastrophes_mean": sum(w["arms"][p]["catastrophes"] for w in worlds) / len(worlds),
            "catastrophes_max": max(w["arms"][p]["catastrophes"] for w in worlds),
            "worst_world": min(rs),
            "p05_world": sorted(rs)[max(0, len(rs) // 20 - 1)],
            "rewards": rs,
        }
    return out


def pub_of(agent):
    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_chain(rows):
    prev, bad = "", 0
    for e in rows:
        payload = {"seq": e["seq"], "tenant": e["tenant"], "agent": e["agent"], "kind": e["kind"],
                   "key": e["key"], "value": e["value"], "nonce": e["nonce"], "prev": prev,
                   "created_at": e["created_at"], "grants_authority": False, "executable": False}
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub_of(e["agent"]))).verify(
                bytes.fromhex(e["sig"]), canon(payload))
            if sha(prev.encode() + canon(payload) + bytes.fromhex(e["sig"])) != e["hash"]:
                bad += 1
        except Exception:  # noqa: BLE001
            bad += 1
        prev = e["hash"]
    return bad


def close(a, b, tol=1e-6):
    return abs(a - b) <= tol


def main(path):
    B = Path(path)
    man = json.loads((B / "E463S_MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    check(man["schema"] == "cain42.e463s.manifest.v1", "manifest schema")
    check(man["evolution"] == "E463-S", "manifest evolution")
    check(man["status"] == STATUS, "mandatory status line")
    check(man["external_review"] == "NOT_OBTAINED", "external review declared")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        sig_ok = True
    except Exception:  # noqa: BLE001
        sig_ok = False
    check(sig_ok, "manifest signature")
    check({n: sha((B / n).read_bytes()) for n in man["files"]} == man["files"], "every declared file hash")
    check(merkle([B / n for n in man["files"]]) == man["merkle_root"], "merkle root")
    check((B / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"], "MERKLE_ROOT.txt")

    rep = json.loads((B / "E463S_RUN_REPORT.json").read_text())
    pre = json.loads((B / "E463S_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E463S_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((B / "SALTS.json").read_text())
    check(sha((B / "E463S_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"],
          "preregistration hash")
    check({k: sha(v.encode()) for k, v in salts.items()} == frz["salt_commitments"], "salt commitment")
    check(rep["verdict"] == "SELECTIVE_GOVERNED_ACTION_SUPPORTED", "verdict")

    for label in ("salt1", "salt2"):
        salt = salts[label]
        R = rep["salts"][label]
        check(R["salt_commit"] == sha(salt.encode()), f"{label} salt commit")
        worlds = []
        for w in range(WORLDS):
            t = build_table(salt, w)
            worlds.append({"world": w, "arms": {p: run_arm(p, t) for p in POLICIES}})
        agg = agg_of(worlds)
        check(len(R["worlds"]) == WORLDS, f"{label} world count")
        for w in range(WORLDS):
            W = R["worlds"][w]
            check(W["world"] == w, f"{label} world {w} index")
            for p in POLICIES:
                A, Bw = agg[p], W["arms"][p]
                check(close(A["rewards"][w], Bw["reward"]), f"{label} w{w} {p} reward")
                check(all(close(worlds[w]["arms"][p]["per_family"][f],
                                Bw["per_family"][str(f)]) for f in range(FAMILIES)),
                      f"{label} w{w} {p} per-family")
                check(all(Bw["counts"][str(f)] == worlds[w]["arms"][p]["counts"][f]
                          and Bw["acts"][str(f)] == worlds[w]["arms"][p]["acts"][f]
                          for f in range(FAMILIES)),
                      f"{label} w{w} {p} counts")
                check(Bw["catastrophes"] == worlds[w]["arms"][p]["catastrophes"],
                      f"{label} w{w} {p} catastrophes")
        for p in POLICIES:
            A = agg[p]
            R2 = R["agg"][p]
            check(close(A["reward_mean"], R2["reward_mean"]), f"{label} {p} reward mean")
            check(close(A["catastrophes_mean"], R2["catastrophes_mean"]), f"{label} {p} catastrophes")
            check(close(A["worst_world"], R2["worst_world"]), f"{label} {p} worst")
            check(close(A["p05_world"], R2["p05_world"]), f"{label} {p} p05")
            check(all(close(A["act_rate"][f], R2["act_rate"][str(f)]) for f in range(FAMILIES)),
                  f"{label} {p} act rate")

        rows = R["memory"]["raw"]
        check(len(rows) == R["memory"]["entries"], f"{label} memory entry count")
        check(verify_chain(rows) == 0 and R["memory"]["bad"] == 0,
              f"{label} every signature and chain link")
        check(all(e["grants_authority"] is False and e["executable"] is False for e in rows),
              f"{label} no entry grants authority")
        check(R["memory"]["duplicate_refused"] == 1, f"{label} duplicate write refused")
        check(R["memory"]["tenant_probe"]["foreign_visible_to_us"] == 0, f"{label} tenant isolation")
        check(R["memory"]["authority"]["allowed"] is False, f"{label} memory cannot authorize")
        check(R["memory"]["tamper_detected"]["detected"] is True, f"{label} tamper detected")
        check(R["drill"]["distinct_pids"] == 4 and R["drill"]["chain_ok"], f"{label} four-process drill")
        # the signed cells must equal the recomputed campaign
        cells = {(e["value"]["world"], e["value"]["policy"], e["value"]["family"]): e
                 for e in rows if e["kind"] == "cell"}
        check(len(cells) == WORLDS * len(POLICIES) * FAMILIES, f"{label} cell count")
        bad = 0
        for w in range(WORLDS):
            for p in POLICIES:
                for f in range(FAMILIES):
                    e = cells.get((w, p, f))
                    if not e or not close(e["value"]["reward"], worlds[w]["arms"][p]["per_family"][f]) \
                            or e["value"]["catastrophes"] != worlds[w]["arms"][p]["catastrophes"]:
                        bad += 1
        check(bad == 0, f"{label} signed cells match the recomputed campaign")

    hyp, s1, s2 = rep["hypotheses"], rep["salts"]["salt1"]["agg"], rep["salts"]["salt2"]["agg"]
    d_always = [s1["calibrated"]["reward_mean"] - s1["always_act"]["reward_mean"],
                s2["calibrated"]["reward_mean"] - s2["always_act"]["reward_mean"]]
    check(hyp["H1_always_act_is_unsafe"]["verdict"] ==
          ("SUPPORTED" if min(d_always) >= 50 else "NOT_SUPPORTED"), "H1 verdict")
    d_mean = [abs(s1["calibrated"]["reward_mean"] - s1["mean"]["reward_mean"]),
              abs(s2["calibrated"]["reward_mean"] - s2["mean"]["reward_mean"])]
    check(hyp["H2_no_expected_cost"]["verdict"] ==
          ("SUPPORTED" if max(d_mean) <= 4 else "NOT_SUPPORTED"), "H2 verdict")
    diffs = [[c - m for c, m in zip(A["calibrated"]["rewards"], A["mean"]["rewards"])] for A in (s1, s2)]
    d_min = [min(d) for d in diffs]
    frac_worse = [sum(1 for x in d if x < -10) / len(d) for d in diffs]
    check(hyp["H3_tail_control"]["verdict"] ==
          ("SUPPORTED" if min(d_min) >= -20 and max(frac_worse) <= 0.15 else "NOT_SUPPORTED"), "H3 verdict")
    cat_c = [s1["calibrated"]["catastrophes_mean"], s2["calibrated"]["catastrophes_mean"]]
    cat_m = [s1["mean"]["catastrophes_mean"], s2["mean"]["catastrophes_mean"]]
    ratio = [cat_m[i] / cat_c[i] if cat_c[i] > 0 else 999.0 for i in range(2)]
    check(hyp["H4_catastrophes_cut"]["verdict"] ==
          ("SUPPORTED" if max(cat_c) <= 1.0 and min(ratio) >= 8 else "NOT_SUPPORTED"), "H4 verdict")
    ledger = all(s["memory"]["chain_ok"] and s["memory"]["bad"] == 0
                 and s["memory"]["duplicate_refused"] == 1
                 and s["memory"]["tenant_probe"]["foreign_visible_to_us"] == 0
                 and s["memory"]["authority"]["allowed"] is False
                 and s["memory"]["tamper_detected"]["detected"]
                 and s["drill"]["distinct_pids"] == 4 and s["drill"]["chain_ok"]
                 for s in (rep["salts"]["salt1"], rep["salts"]["salt2"]))
    check(hyp["H5_ledger_replays_and_grants_nothing"]["verdict"] ==
          ("SUPPORTED" if ledger else "NOT_SUPPORTED"), "H5 verdict")
    repl = all(hyp[k]["verdict"] == "SUPPORTED" for k in
               ("H1_always_act_is_unsafe", "H2_no_expected_cost", "H3_tail_control", "H4_catastrophes_cut"))
    check(hyp["H6_replication"]["verdict"] == ("SUPPORTED" if repl else "NOT_SUPPORTED"), "H6 verdict")
    check(hyp["H7_external_review"]["verdict"] == "BLOCKED", "H7 external review blocked")
    ok = all(hyp[k]["verdict"] == "SUPPORTED" for k in
             ("H1_always_act_is_unsafe", "H2_no_expected_cost", "H3_tail_control",
              "H4_catastrophes_cut", "H5_ledger_replays_and_grants_nothing", "H6_replication"))
    check(ok and rep["verdict"] == "SELECTIVE_GOVERNED_ACTION_SUPPORTED", "verdict rule")
    check(pre["design"]["worlds_per_salt"] == WORLDS and pre["design"]["fallback"] == FALLBACK,
          "preregistration design")
    check(pre["salts_commitment"] == frz["salt_commitments"], "preregistration salts")
    dev = json.loads((B / "E463S_DEVIATIONS.json").read_text())
    check(dev.get("deviations") is not None and any(d.get("id") == "D1" for d in dev["deviations"]),
          "deviations recorded (incl. the v1 near-miss)")
    v1 = json.loads((B / "E463S_RUN_REPORT.v1.json").read_text())
    check(v1["verdict"] == "NOT_SUPPORTED" and
          v1["hypotheses"]["H3_tail_control"]["verdict"] == "NOT_SUPPORTED",
          "v1 near-miss preserved and labelled")

    print(f"{CH['ok']}/{CH['n']} checks")
    for f in CH["fail"]:
        print("FAIL:", f)
    return 0 if CH["ok"] == CH["n"] else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else str(Path(__file__).resolve().parent)))
