#!/usr/bin/env python3
"""E461-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 bounded campaign from the revealed salts**: the outcome tables,
all seven policies, every per-world solve/spend/attempt row, the budget discipline, the replay of
the screen policy from the signed stream, and every hypothesis.

Usage: python3 verify_e461m_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
PER_FAMILY = 144
STREAM = FAMILIES * PER_FAMILY
BUDGET = 720
ROLES = ["S", "E", "C", "M", "W", "V"]
ROLE_P = {"S": 0.95, "E": 0.62, "C": 0.25, "M": 0.55, "W": 0.30, "V": 0.20}
ROLE_C = {"S": 6, "E": 2, "C": 1, "M": 3, "W": 4, "V": 5}
COMP = [[0.0] * AGENTS for _ in range(FAMILIES)]
COST = [[0] * AGENTS for _ in range(FAMILIES)]
for _f in range(FAMILIES):
    for _k, _r in enumerate(ROLES):
        _a = (_f + _k) % AGENTS
        COMP[_f][_a] = ROLE_P[_r]
        COST[_f][_a] = ROLE_C[_r]
ARMS = ["oracle", "screen", "static", "ratio_ucb", "comp_ucb", "amnesiac", "random"]
WORLDS = 48
SCREEN_CELLS = 3
SCREEN_SAMPLES = 3
RESET_EVERY = 48
TENANT = "cain42-e461m"
SEED = "e461m"
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 smoothed(n, w):
    return (w + 1.0) / (n + 2.0)


def ratio(f, a):
    return COMP[f][a] / COST[f][a]


def pick_screen(f, afford, n, w):
    order = sorted(range(AGENTS), key=lambda a: (COST[f][a], a))[:SCREEN_CELLS]
    for a in order:
        if n[f][a] < SCREEN_SAMPLES and a in afford:
            return a
    return max(afford, key=lambda a: (smoothed(n[f][a], w[f][a]) / COST[f][a], -a))


def pick_ucb(f, afford, n, w, total, cost_aware):
    def idx(a):
        m = (w[f][a] + 0.5) / (n[f][a] + 1)
        bonus = math.sqrt(2 * math.log(total + 1) / (n[f][a] + 1))
        return (m + bonus) / COST[f][a] if cost_aware else (m + bonus)
    return max(afford, key=lambda a: (idx(a), -a))


def random_for(salt, world):
    return random.Random(int(sha(canon([salt, world, "rng"]))[:16], 16))


def build_table(salt, world):
    r = random.Random(int(sha(canon([salt, world, "table"]))[:16], 16))
    table = [[[0] * PER_FAMILY for _ in range(AGENTS)] for _ in range(FAMILIES)]
    for f in range(FAMILIES):
        for k in range(PER_FAMILY):
            for a in range(AGENTS):
                table[f][a][k] = 1 if r.random() < COMP[f][a] else 0
    return table


def run_arm(arm, table, salt, world):
    spent = solved = attempts = 0
    n = [[0] * AGENTS for _ in range(FAMILIES)]
    w = [[0] * AGENTS for _ in range(FAMILIES)]
    occ = [0] * FAMILIES
    per_family = [0] * FAMILIES
    rng = random_for(salt, world)
    while attempts < STREAM:
        f = attempts % FAMILIES
        if occ[f] >= PER_FAMILY:
            break
        afford = [a for a in range(AGENTS) if spent + COST[f][a] <= BUDGET]
        if not afford:
            break
        total = sum(n[ff][aa] for ff in range(FAMILIES) for aa in range(AGENTS))
        if arm == "oracle":
            a = max(afford, key=lambda a: (ratio(f, a), -a))
        elif arm == "random":
            a = rng.choice(afford)
        elif arm in ("screen", "amnesiac"):
            if arm == "amnesiac" and attempts > 0 and attempts % RESET_EVERY == 0:
                n = [[0] * AGENTS for _ in range(FAMILIES)]
                w = [[0] * AGENTS for _ in range(FAMILIES)]
            a = pick_screen(f, afford, n, w)
        elif arm == "static":
            cal = [a for a in afford if n[f][a] == 0]
            if cal:
                a = min(cal, key=lambda a: (COST[f][a], a))
            else:
                a = max(afford, key=lambda a: (smoothed(n[f][a], w[f][a]) / COST[f][a], -a))
        elif arm in ("ratio_ucb", "comp_ucb"):
            a = pick_ucb(f, afford, n, w, total, arm == "ratio_ucb")
        else:
            raise ValueError(arm)
        ok = table[f][a][occ[f]]
        spent += COST[f][a]
        solved += ok
        per_family[f] += ok
        attempts += 1
        occ[f] += 1
        n[f][a] += 1
        w[f][a] += ok
    return {"solved": solved, "spent": spent, "attempts": attempts, "per_family": per_family}


def replay_screen(records):
    n = [[0] * AGENTS for _ in range(FAMILIES)]
    w = [[0] * AGENTS for _ in range(FAMILIES)]
    solved = 0
    ok_all = True
    for rec in records:
        f, a = rec["family"], rec["agent"]
        afford = [b for b in range(AGENTS) if rec["spent_before"] + COST[f][b] <= BUDGET]
        if pick_screen(f, afford, n, w) != a:
            ok_all = False
        if rec["spent_after"] != rec["spent_before"] + COST[f][a]:
            ok_all = False
        solved += rec["success"]
        n[f][a] += 1
        w[f][a] += rec["success"]
    return ok_all, 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 / "E461M_MANIFEST.json").read_text())
    c.eq(man["schema"], "cain42.e461m.manifest.v1", "manifest schema")
    c.eq(man["evolution"], "E461-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 / "E461M_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    frz = json.loads((root / "E461M_PREREGISTRATION_FREEZE.json").read_text())
    pre = json.loads((root / "E461M_PREREGISTRATION.json").read_text())
    c.eq(frz["preregistration_sha256"], sha((root / "E461M_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) for w in range(WORLDS)]
        for arm in ARMS:
            runs = [run_arm(arm, t, salt, w) for w, t in enumerate(tables)]
            got = {
                "solved": [r["solved"] for r in runs],
                "spent": [r["spent"] for r in runs],
                "attempts": [r["attempts"] for r in runs],
                "per_family": [r["per_family"] for r in runs],
                "solved_mean": mean([r["solved"] for r in runs]),
                "spent_mean": mean([r["spent"] for r in runs]),
                "attempts_mean": mean([r["attempts"] for r in runs]),
                "spent_max": max(r["spent"] for r in runs),
                "cost_per_solve": mean([r["spent"] for r in runs])
                / max(1e-9, mean([r["solved"] for r in runs])),
            }
            for k in ("solved", "spent", "attempts", "per_family"):
                c.eq(got[k], cell["arms"][arm][k], f"{name} {arm} {k}")
            for k in ("solved_mean", "spent_mean", "attempts_mean", "cost_per_solve"):
                c.close(got[k], cell["arms"][arm][k], f"{name} {arm} {k}")
            c.eq(got["spent_max"], cell["arms"][arm]["spent_max"], f"{name} {arm} spent_max")
            res[(name, arm)] = got
        m = cell["memory"]
        entries = m["raw"]
        c.eq(len(entries), m["entries"], f"{name} memory entry count")
        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 = [e["value"] for e in entries]
        ok, solved = replay_screen(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 a(s, arm):
        return res[(s, arm)]

    h1 = all(a(s, "comp_ucb")["solved_mean"] <= 0.65 * a(s, "oracle")["solved_mean"]
             for s in ("salt1", "salt2"))
    c.ok(h1, "H1 competence wastes budget")
    h2 = all(a(s, "screen")["solved_mean"] >= 0.90 * a(s, "oracle")["solved_mean"]
             for s in ("salt1", "salt2"))
    c.ok(h2, "H2 screen recovers oracle")
    h3 = all(a(s, "screen")["solved_mean"] >= a(s, "comp_ucb")["solved_mean"] + 60
             for s in ("salt1", "salt2"))
    c.ok(h3, "H3 screen beats competence")
    h4 = all(a(s, "amnesiac")["solved_mean"] <= 0.90 * a(s, "screen")["solved_mean"]
             for s in ("salt1", "salt2"))
    c.ok(h4, "H4 memory required")
    h5 = all(all(a(s, arm)["spent_max"] <= BUDGET for arm in ARMS)
             and a(s, "screen")["spent_mean"] >= 0.95 * BUDGET
             and a(s, "screen")["cost_per_solve"] <= 0.75 * a(s, "comp_ucb")["cost_per_solve"]
             for s in ("salt1", "salt2"))
    c.ok(h5, "H5 budget discipline")
    c.eq(rep["drill"]["distinct_pids"], 4, "drill distinct PIDs")
    c.eq(rep["drill"]["chain_valid"], True, "drill chain valid")
    c.eq(rep["verdict"], "BUDGET_AWARE_GOVERNED_ROUTING_SUPPORTED", "verdict")
    for k in ("H1_competence_wastes_budget", "H2_screen_recovers_oracle",
              "H3_screen_beats_competence", "H4_memory_required", "H5_budget_discipline",
              "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("E461-M VERIFICATION FAILED")
        for b in c.bad[:20]:
            print(" -", b)
        return 1
    print(f"E461-M VERIFIED {c.n}/{c.n} checks; {STATUS}")
    return 0


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