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

Verifies the manifest, every file, the salt commitment, every signed experiment in the governed
memory, and **re-derives the whole campaign from the revealed salts**: the 16 permutations, the
240 pairs and their behaviours, the 24 sealed tasks, all eight coverage policies, every per-world
coverage/solve row, the poison accounting, the replay, and every hypothesis.

Usage: python3 verify_cdm_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

N = 16
M = 64
PER = 60
AGENTS = 4
PAIRS = N * (N - 1)
TASKS = 24
ARMS = ["shared", "independent", "partitioned", "shared_churn", "independent_churn",
        "random_shared", "poison_trust", "poison_verified"]
WORLDS = 48
TENANT = "cain42-cdm"
SEED = "cdm"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
AGENT_NAMES = ["atlas", "borealis", "cetus", "draco", "mallory"]


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 perms(salt, world):
    out = []
    for i in range(N):
        r = random.Random(int(sha(canon([salt, world, "perm", i]))[:16], 16))
        p = list(range(M))
        r.shuffle(p)
        out.append(p)
    return out


def comp(p, q):
    return [p[q[x]] for x in range(M)]


def build(salt, world):
    ps = perms(salt, world)
    pairs = [(a, b) for a in range(N) for b in range(N) if a != b]
    beh = {pr: tuple(comp(ps[pr[0]], ps[pr[1]])) for pr in pairs}
    ids = {}
    by_id = {}
    for pr, b in beh.items():
        if b not in by_id:
            by_id[b] = len(by_id)
        ids[pr] = by_id[b]
    r = random.Random(int(sha(canon([salt, world, "tasks"]))[:16], 16))
    tasks = []
    while len(tasks) < TASKS:
        a, b, c, d = r.sample(range(N), 4)
        t = (ids[(a, b)], ids[(c, d)])
        if t not in tasks:
            tasks.append(t)
    return {"ps": ps, "pairs": pairs, "beh": beh, "ids": ids,
            "tasks": tasks, "n_behaviours": len(by_id)}


def beh_hash(d, pr):
    return sha(canon(list(d["beh"][pr])))


def order_for(salt, world):
    return sorted(range(PAIRS), key=lambda i: sha(canon([salt, world, "order", i])))


def pick_shared(order, tried, n):
    out = []
    for i in order:
        if len(out) >= n:
            break
        if i in tried:
            continue
        tried.add(i)
        out.append(i)
    return out


def run_arm(arm, d, salt, world):
    pairs = d["pairs"]
    order = order_for(salt, world)
    tried = set()
    executed = set()
    entries = 0
    false_accepted = 0
    fake = set()
    if arm in ("poison_trust", "poison_verified"):
        fake = set(order[-60:])
        entries += len(fake)
        if arm == "poison_trust":
            tried |= fake
            false_accepted = 60

    def execute(i):
        nonlocal entries
        executed.add(i)
        entries += 1

    if arm in ("shared", "poison_trust", "poison_verified"):
        for k in range(4):
            for i in pick_shared(order, tried, PER):
                execute(i)
    elif arm == "shared_churn":
        for k in range(4):
            for i in pick_shared(order, tried, PER):
                execute(i)
    elif arm == "partitioned":
        for k in range(4):
            for i in order[k * PER:(k + 1) * PER]:
                tried.add(i)
                execute(i)
    elif arm in ("independent", "random_shared", "independent_churn"):
        for k in range(4):
            rng = random.Random(int(sha(canon([salt, world, arm, k]))[:16], 16))
            for _ in range(PER):
                i = rng.randrange(PAIRS)
                tried.add(i)
                if i not in executed:
                    execute(i)
    else:
        raise ValueError(arm)
    lib = {d["ids"][pairs[i]] for i in executed}
    solved = sum(1 for x, y in d["tasks"] if x in lib and y in lib)
    return {"pairs": len(executed), "behaviours": len(lib), "solved": solved,
            "entries": entries, "false_accepted": false_accepted}


def replay_shared(records, d, salt, world):
    order = order_for(salt, world)
    pos = {i: k for k, i in enumerate(order)}
    pair_index = {pr: i for i, pr in enumerate(d["pairs"])}
    seen = set()
    lib = set()
    last = {a: -1 for a in AGENT_NAMES[:4]}
    ok = True
    for rec in records:
        v = rec["value"]
        if v.get("fake"):
            continue
        pr = tuple(v["pair"])
        i = pair_index.get(pr)
        if i is None or i in seen or v["behaviour"] != beh_hash(d, pr):
            ok = False
            continue
        agent = v["agent"]
        if agent in last and pos[i] < last[agent]:
            ok = False
        if agent in last:
            last[agent] = pos[i]
        seen.add(i)
        lib.add(d["ids"][pr])
    solved = sum(1 for x, y in d["tasks"] if x in lib and y in lib)
    return ok, len(seen), 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 / "CDM_MANIFEST.json").read_text())
    c.eq(man["schema"], "cain42.cdm.manifest.v1", "manifest schema")
    c.eq(man["evolution"], "CDM", "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 / "CDM_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    frz = json.loads((root / "CDM_PREREGISTRATION_FREEZE.json").read_text())
    pre = json.loads((root / "CDM_PREREGISTRATION.json").read_text())
    c.eq(frz["preregistration_sha256"], sha((root / "CDM_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 AGENT_NAMES}
    res = {}
    for name in ("salt1", "salt2"):
        salt = salts[name]
        cell = rep["scenarios"][name]
        ds = [build(salt, w) for w in range(WORLDS)]
        for arm in ARMS:
            runs = [run_arm(arm, d, salt, w) for w, d in enumerate(ds)]
            got = {
                "pairs": [r["pairs"] for r in runs],
                "behaviours": [r["behaviours"] for r in runs],
                "solved": [r["solved"] for r in runs],
                "entries": [r["entries"] for r in runs],
                "pairs_mean": mean([r["pairs"] for r in runs]),
                "behaviours_mean": mean([r["behaviours"] for r in runs]),
                "solved_mean": mean([r["solved"] for r in runs]),
                "false_accepted": runs[0]["false_accepted"],
            }
            for k in ("pairs", "behaviours", "solved", "entries", "false_accepted"):
                c.eq(got[k], cell["arms"][arm][k], f"{name} {arm} {k}")
            for k in ("pairs_mean", "behaviours_mean", "solved_mean"):
                c.close(got[k], cell["arms"][arm][k], f"{name} {arm} {k}")
            res[(name, arm)] = got
        m = cell["memory"]
        entries = m["raw"]
        c.eq(len(entries), 240, 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")
        ok, seen, solved = replay_shared(entries, ds[0], salt, 0)
        c.eq(ok, True, f"{name} coverage replays from memory")
        c.eq(seen, m["replay_pairs"], f"{name} replay pairs")
        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, "shared")["pairs_mean"] >= 235 and a(s, "independent")["pairs_mean"] <= 180
             and a(s, "shared")["solved_mean"] >= 22 and a(s, "independent")["solved_mean"] <= 14
             for s in ("salt1", "salt2"))
    c.ok(h1, "H1 coverage dividend")
    h2 = all(a(s, "shared")["solved_mean"] >= a(s, "partitioned")["solved_mean"]
             and a(s, "partitioned")["solved_mean"] >= 23 for s in ("salt1", "salt2"))
    c.ok(h2, "H2 matches static partition")
    h3 = all(a(s, "shared_churn")["solved_mean"] >= 22
             and a(s, "independent_churn")["solved_mean"] <= 16 for s in ("salt1", "salt2"))
    c.ok(h3, "H3 churn")
    h4 = all(a(s, "poison_trust")["solved_mean"] <= 16
             and a(s, "poison_verified")["solved_mean"] >= 23
             and a(s, "poison_verified")["solved_mean"] - a(s, "poison_trust")["solved_mean"] >= 8
             for s in ("salt1", "salt2"))
    c.ok(h4, "H4 verify the record")
    h5 = all(a(s, "random_shared")["solved_mean"] <= 16 for s in ("salt1", "salt2"))
    c.ok(h5, "H5 memory must be read")
    c.eq(rep["drill"]["distinct_pids"], 4, "drill distinct PIDs")
    c.eq(rep["drill"]["chain_valid"], True, "drill chain valid")
    c.eq(rep["verdict"], "COVERAGE_DIVIDEND_SUPPORTED", "verdict")
    for k in ("H1_coverage_dividend", "H2_matches_static_partition", "H3_churn",
              "H4_verify_the_record", "H5_memory_must_be_read", "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("CDM VERIFICATION FAILED")
        for b in c.bad[:20]:
            print(" -", b)
        return 1
    print(f"CDM VERIFIED {c.n}/{c.n} checks; {STATUS}")
    return 0


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