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

Verifies the manifest, every file, the salt commitment, every signed attempt in the governed memory,
and **re-derives the whole campaign from the revealed salts**: the success tables, all six policies,
the detection and recovery statistics, the stationary false-alarm controls, the CUSUM replay from the
signed stream, and every hypothesis.

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

import hashlib
import json
import math
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
AGENTS = 6
PHASES = 3
PER_PHASE = 192
PER_FAMILY_PHASE = 48
OCCURRENCES = 144
CHANGE_PHASE = 1
CHANGE_I = 96
CHANGE_ATTEMPT = 288
BASE = [
    [0.90, 0.55, 0.50, 0.45, 0.40, 0.35],
    [0.50, 0.90, 0.55, 0.45, 0.40, 0.35],
    [0.45, 0.50, 0.90, 0.55, 0.40, 0.35],
    [0.40, 0.45, 0.50, 0.90, 0.55, 0.35],
]
ARMS = ["oracle", "cusum", "sliding32", "static", "ucb", "amnesiac"]
WORLDS = 48
STATIONARY = 48
CUSUM_K = 0.05
CUSUM_H = 1.2
CUSUM_MU = 0.55
MIN_MON = 8
CAL = 2
RECAL = 2
SLIDE = 32
TENANT = "cain42-e459m"
SEED = "e459m"
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 competence(f, a, post, changing=True):
    if changing and post and f == 0 and a == 0:
        return 0.35
    if changing and post and f == 0 and a == 5:
        return 0.90
    return BASE[f][a]


def is_post(phase, i, changing=True):
    return changing and ((phase == CHANGE_PHASE and i >= CHANGE_I) or phase == 2)


def family_of(attempt):
    return attempt % FAMILIES


def occurrence_of(attempt):
    phase, i = divmod(attempt, PER_PHASE)
    return phase * PER_FAMILY_PHASE + i // FAMILIES


def build_table(salt, world, changing=True):
    r = random.Random(int(sha(canon([salt, world, "table", bool(changing)]))[:16], 16))
    table = [[[0] * OCCURRENCES for _ in range(AGENTS)] for _ in range(FAMILIES)]
    for f in range(FAMILIES):
        for k in range(OCCURRENCES):
            phase, kin = divmod(k, PER_FAMILY_PHASE)
            post = is_post(phase, kin * FAMILIES, changing)
            for a in range(AGENTS):
                table[f][a][k] = 1 if r.random() < competence(f, a, post, changing) else 0
    return table


def choose(arm, st, f):
    obs = st["obs"]
    if arm == "oracle":
        return max(range(AGENTS), key=lambda a: competence(f, a, st["post"]))
    if arm == "amnesiac":
        return st["occ"] % AGENTS
    if arm == "ucb":
        n = sum(len(obs.get((f, a), [])) for a in range(AGENTS))
        def u(a):
            v = obs.get((f, a), [])
            if not v:
                return 1e9
            return statistics.mean(v) + math.sqrt(2 * math.log(max(2, n)) / len(v))
        return max(range(AGENTS), key=lambda a: (u(a), -a))
    cal = [a for a in range(AGENTS) if len(obs.get((f, a), [])) < CAL]
    if cal:
        return cal[0]
    forced = [a for a in range(AGENTS) if st["forced"].get((f, a), 0) > 0]
    if forced:
        return forced[0]
    def m(a):
        v = obs.get((f, a), [])
        if arm == "sliding32":
            v = v[-SLIDE:]
        return statistics.mean(v) if v else 1e9
    return max(range(AGENTS), key=lambda a: (m(a), -a))


def run_arm(arm, table, changing):
    st = {"obs": {}, "forced": {}, "cus": {}, "post": False, "occ": 0}
    solved = post_solved = 0
    alarms = []
    first_post = None
    for attempt in range(PHASES * PER_PHASE):
        phase, i = divmod(attempt, PER_PHASE)
        f = family_of(attempt)
        occ = occurrence_of(attempt)
        post = is_post(phase, i, changing)
        st["post"], st["occ"] = post, occ
        a = choose(arm, st, f)
        ok = table[f][a][occ]
        st["obs"].setdefault((f, a), []).append(ok)
        if st["forced"].get((f, a), 0) > 0:
            st["forced"][(f, a)] -= 1
        solved += ok
        if post:
            post_solved += ok
        if arm == "cusum":
            v = st["obs"][(f, a)]
            if len(v) >= MIN_MON:
                lo = st["cus"].get((f, a), 0.0)
                lo = max(0.0, lo + (CUSUM_MU - v[-1] - CUSUM_K))
                st["cus"][(f, a)] = lo
                if lo > CUSUM_H:
                    alarms.append(attempt)
                    if post and f == 0 and first_post is None:
                        first_post = attempt
                    for b in range(AGENTS):
                        st["obs"][(f, b)] = st["obs"].get((f, b), [])[-6:]
                        st["forced"][(f, b)] = RECAL
                    st["cus"] = {k: 0.0 for k in st["cus"] if k[0] == f}
    return {"solved": solved, "post_solved": post_solved, "alarms": alarms,
            "first_post": first_post}


def replay_cusum(records):
    st = {"obs": {}, "forced": {}, "cus": {}, "post": False, "occ": 0}
    solved = 0
    ok = True
    for rec in records:
        attempt, f, a = rec["attempt"], rec["family"], rec["agent"]
        st["post"] = bool(rec["post"])
        st["occ"] = occurrence_of(attempt)
        if choose("cusum", st, f) != a:
            ok = False
        success = rec["success"]
        st["obs"].setdefault((f, a), []).append(success)
        if st["forced"].get((f, a), 0) > 0:
            st["forced"][(f, a)] -= 1
        solved += success
        v = st["obs"][(f, a)]
        if len(v) >= MIN_MON:
            lo = st["cus"].get((f, a), 0.0)
            lo = max(0.0, lo + (CUSUM_MU - v[-1] - CUSUM_K))
            st["cus"][(f, a)] = lo
            if lo > CUSUM_H:
                for b in range(AGENTS):
                    st["obs"][(f, b)] = st["obs"].get((f, b), [])[-6:]
                    st["forced"][(f, b)] = RECAL
                st["cus"] = {k: 0.0 for k in st["cus"] if k[0] == f}
    return ok, solved


def pubhex(agent):
    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_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"")


class Checker:
    def __init__(self):
        self.n = 0
        self.bad = []

    def ok(self, cond, name, detail=""):
        self.n += 1
        if not cond:
            self.bad.append(f"{name}: {detail}")

    def eq(self, a, b, name):
        self.ok(a == b, name, f"{a!r} != {b!r}")

    def close(self, a, b, name):
        self.ok(abs(a - b) < 1e-9, name, f"{a!r} != {b!r}")


def verify(root: Path):
    c = Checker()
    man = json.loads((root / "E459M_MANIFEST.json").read_text())
    c.eq(man["schema"], "cain42.e459m.manifest.v1", "manifest schema")
    c.eq(man["evolution"], "E459-M", "evolution")
    c.eq(man["status"], STATUS, "status line")
    for name, h in man["files"].items():
        p = root / name
        c.ok(p.exists(), f"file present {name}")
        if p.exists():
            c.eq(sha(p.read_bytes()), h, f"file hash {name}")
    c.eq(merkle([root / n for n in man["files"]]), man["merkle_root"], "merkle root")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon({k: man[k] for k in man if k != "signature"}))
        sig_ok = True
    except Exception:
        sig_ok = False
    c.ok(sig_ok, "manifest signature")
    rep = json.loads((root / "E459M_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    frz = json.loads((root / "E459M_PREREGISTRATION_FREEZE.json").read_text())
    pre = json.loads((root / "E459M_PREREGISTRATION.json").read_text())
    c.eq(frz["preregistration_sha256"], sha((root / "E459M_PREREGISTRATION.json").read_bytes()),
         "prereg hash")
    c.eq({k: sha(v.encode()) for k, v in salts.items()}, frz["salt_commitments"], "salt commitment")
    c.eq(pre["salts_commitment"], frz["salt_commitments"], "prereg salt commitment")

    pubs = {a: pubhex(a) for a in ["atlas", "borealis", "cetus", "draco", "mallory"]}
    res = {}
    for name in ("salt1", "salt2"):
        salt = salts[name]
        cell = rep["scenarios"][name]
        tables = [build_table(salt, w, True) for w in range(WORLDS)]
        for arm in ARMS:
            runs = [run_arm(arm, t, True) for t in tables]
            got = {
                "solved_mean": mean([r["solved"] for r in runs]),
                "post_solved_mean": mean([r["post_solved"] for r in runs]),
                "post_solved": [r["post_solved"] for r in runs],
                "solved": [r["solved"] for r in runs],
                "alarms_mean": mean([len(r["alarms"]) for r in runs]),
                "detected": sum(1 for r in runs if r["first_post"] is not None),
                "within_48": sum(1 for r in runs if r["first_post"] is not None
                                 and r["first_post"] - CHANGE_ATTEMPT <= 48),
                "delays": [r["first_post"] - CHANGE_ATTEMPT for r in runs
                           if r["first_post"] is not None],
            }
            for k in ("solved_mean", "post_solved_mean", "alarms_mean"):
                c.close(got[k], cell["change"][arm][k], f"{name} {arm} {k}")
            for k in ("post_solved", "solved", "delays"):
                c.eq(got[k], cell["change"][arm][k], f"{name} {arm} {k}")
            for k in ("detected", "within_48"):
                c.eq(got[k], cell["change"][arm][k], f"{name} {arm} {k}")
            res[(name, arm)] = got
        # stationary
        st_tables = [build_table(salt, 1000 + w, False) for w in range(STATIONARY)]
        st = [run_arm("cusum", t, False) for t in st_tables]
        alarms = [len(r["alarms"]) for r in st]
        c.eq(alarms, cell["stationary"]["alarms"], f"{name} stationary alarms")
        c.close(mean(alarms), cell["stationary"]["mean"], f"{name} stationary mean")
        c.eq(max(alarms), cell["stationary"]["max"], f"{name} stationary max")
        # memory
        m = cell["memory"]
        entries = m["raw"]
        c.eq(len(entries), 576, f"{name} memory entries")
        c.eq(verify_entries(entries, pubs), [], f"{name} memory chain+signatures")
        c.eq(m["chain_valid"], not verify_entries(entries, pubs), f"{name} chain flag")
        records = [{"attempt": e["value"]["attempt"], "family": e["value"]["family"],
                    "agent": e["value"]["agent"], "post": e["value"]["post"],
                    "success": e["value"]["success"]} for e in entries]
        ok, solved = replay_cusum(records)
        c.eq(ok, True, f"{name} policy replays from memory")
        c.eq(solved, m["replay_solved"], f"{name} replay solved")
        c.eq(m["replay_ok"], True, f"{name} replay flag")
        c.eq(m["live_solved"], solved, f"{name} live == replay")
        c.eq(m["tenant_probe"]["foreign_visible_to_us"], 0, f"{name} tenant isolation")
        c.eq(m["tamper_detected"], True, f"{name} tamper detected")
        c.ok(all(not p["granted"] for p in m["authority_probes"]), f"{name} no authority")

    def post(s, arm):
        return res[(s, arm)]["post_solved_mean"]

    h1 = all(post(s, "static") <= post(s, "oracle") - 40 for s in ("salt1", "salt2"))
    c.ok(h1, "H1 regime change hurts")
    h2 = all(res[(s, "cusum")]["within_48"] >= 40 and post(s, "cusum") >= 0.90 * post(s, "oracle")
             for s in ("salt1", "salt2"))
    c.ok(h2, "H2 detect and recover")
    h3 = all(rep["scenarios"][s]["stationary"]["mean"] <= 1.5
             and rep["scenarios"][s]["stationary"]["max"] <= 6 for s in ("salt1", "salt2"))
    c.ok(h3, "H3 false alarms bounded")
    h4 = all(post(s, "cusum") >= post(s, "static") + 20
             and post(s, "cusum") >= post(s, "sliding32") + 5 for s in ("salt1", "salt2"))
    c.ok(h4, "H4 beats baselines")
    h5 = all(post(s, "amnesiac") <= 0.70 * post(s, "cusum") for s in ("salt1", "salt2"))
    c.ok(h5, "H5 memory required")
    c.eq(rep["drill"]["distinct_pids"], 4, "drill distinct PIDs")
    c.eq(rep["drill"]["chain_valid"], True, "drill chain valid")
    c.eq(rep["verdict"], "NONSTATIONARY_GOVERNED_ROUTING_SUPPORTED", "verdict")
    for k in ("H1_regime_change_hurts", "H2_detect_and_recover", "H3_false_alarms_bounded",
              "H4_beats_baselines", "H5_memory_required", "H6_governance"):
        c.eq(rep["hypotheses"][k]["verdict"], "SUPPORTED", f"{k} verdict")
    c.eq(rep["hypotheses"]["H7_external_review"]["verdict"], "BLOCKED", "H7 verdict")
    return c


def main():
    root = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path(__file__).resolve().parent
    c = verify(root)
    if c.bad:
        print("E459-M VERIFICATION FAILED")
        for b in c.bad[:20]:
            print(" -", b)
        return 1
    print(f"E459-M VERIFIED {c.n}/{c.n} checks; {STATUS}")
    return 0


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