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

It re-verifies the signed manifest, every evidence file, every memory entry's Ed25519 signature and
SHA-256 link, the salt commitment, and then **re-derives the whole result from the revealed salts and
the declared design**: the six primitives, the agents' macros, the retained trace, the bounded word
search, the exact 5040-point verification, the parity boundary and the sealed capability of every
arm.

Usage: python3 verify_e455m_offline.py [bundle_dir]
Exit 0 only if every check passes.
"""
from __future__ import annotations

import hashlib
import json
import sys
from collections import deque
from pathlib import Path

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

N = 7
IDENTITY = tuple(range(N))
SEED = "e455m"
AGENTS = ["atlas", "borealis", "cetus", "draco"]
DEPARTED = "cetus"
POISON = "mallory"
OWN = {"atlas": [0, 1], "borealis": [2, 3], "cetus": [4, 5], "draco": [1, 5]}
SURVIVORS = [0, 1, 2, 3, 5]
TRACE = [(4, 5), (5, 4)]
EVEN_PRIMS = [1, 5]
LOST = 4
DEPTH = 3
SEALED = 24
TENANT = "cain42-e455m"
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 compose(a, b):
    return tuple(a[b[i]] for i in range(N))


def invert(a):
    out = [0] * N
    for i, x in enumerate(a):
        out[x] = i
    return tuple(out)


def parity(a):
    seen = [False] * N
    p = 0
    for i in range(N):
        if not seen[i]:
            j = i
            c = 0
            while not seen[j]:
                seen[j] = True
                j = a[j]
                c += 1
            p ^= (c - 1) & 1
    return p


def cycle(*cycles):
    a = list(range(N))
    for c in cycles:
        for i in range(len(c)):
            a[c[i]] = c[(i + 1) % len(c)]
    return tuple(a)


PRIMITIVES = [cycle((0, 1)), cycle((0, 1, 2, 3, 4, 5, 6)), cycle((0, 6), (1, 5), (2, 4)),
              cycle((0, 2, 4, 6), (1, 3, 5)), cycle((3, 4)), cycle((0, 3), (1, 5))]


def word(seq):
    t = IDENTITY
    for i in seq:
        t = compose(PRIMITIVES[i], t)
    return t


def closure(behs):
    gens = []
    for b in behs:
        gens.append(b)
        gens.append(invert(b))
    seen = {IDENTITY}
    q = deque([IDENTITY])
    while q:
        x = q.popleft()
        for g in gens:
            y = compose(g, x)
            if y not in seen:
                seen.add(y)
                q.append(y)
    return seen


def steps(gens):
    out = []
    for label, b in gens:
        out.append((label, b))
        out.append((f"inv:{label}", invert(b)))
    return out


def bfs(gens, target, max_depth, cap=2_000_000):
    st = steps(gens)
    seen = {IDENTITY}
    frontier = [(IDENTITY, [])]
    expanded = 0
    if target == IDENTITY:
        return {"found": True, "depth": 0, "word": [], "expanded": 0, "states": 1}
    for depth in range(1, max_depth + 1):
        nxt = []
        for b, prog in frontier:
            for label, g in st:
                expanded += 1
                if expanded > cap:
                    return {"found": False, "depth": None, "word": None, "expanded": expanded,
                            "states": len(seen), "capped": True}
                nb = compose(g, b)
                if nb in seen:
                    continue
                if nb == target:
                    return {"found": True, "depth": depth, "word": prog + [label],
                            "expanded": expanded, "states": len(seen) + 1}
                seen.add(nb)
                nxt.append((nb, prog + [label]))
        frontier = nxt
        if not frontier:
            break
    return {"found": False, "depth": None, "word": None, "expanded": expanded,
            "states": len(seen), "capped": False}


def reachable(gens, max_depth):
    seen = {IDENTITY}
    frontier = [IDENTITY]
    for _ in range(max_depth):
        st = steps(gens)
        nxt = []
        for b in frontier:
            for _label, g in st:
                nb = compose(g, b)
                if nb in seen:
                    continue
                seen.add(nb)
                nxt.append(nb)
        frontier = nxt
        if not frontier:
            break
    return seen


def rng(*parts):
    import random
    return random.Random(int(sha(canon(list(parts)))[:16], 16))


def gen_targets(salt, scenario):
    r = rng(salt, scenario, "targets")
    seen, out = set(), []
    while len(out) < SEALED:
        seq = [r.randrange(6) for _ in range(DEPTH - 1)]
        seq.insert(r.randrange(DEPTH), LOST)
        b = word(seq)
        if b in seen:
            continue
        seen.add(b)
        out.append(list(b))
    return out


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 verify(root: Path):
    c = Checker()
    man = json.loads((root / "E455M_MANIFEST.json").read_text())
    c.eq(man["schema"], "cain42.e455m.manifest.v1", "manifest schema")
    c.eq(man["evolution"], "E455-M", "evolution")
    c.eq(man["status"], STATUS, "status line")
    # file hashes
    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}")
    files = [root / name for name in man["files"]]
    c.eq(merkle(files), man["merkle_root"], "merkle root")
    # manifest signature
    body = canon({k: man[k] for k in man if k != "signature"})
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), body)
        sig_ok = True
    except Exception:
        sig_ok = False
    c.ok(sig_ok, "manifest signature")

    rep = json.loads((root / "E455M_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    frz = json.loads((root / "E455M_PREREGISTRATION_FREEZE.json").read_text())
    pre = json.loads((root / "E455M_PREREGISTRATION.json").read_text())
    c.eq(frz["preregistration_sha256"], sha((root / "E455M_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")
    c.eq([parity(p) for p in PRIMITIVES], [1, 0, 1, 1, 1, 0], "primitive parities")

    pubs = {a: pubhex(a) for a in AGENTS + [POISON]}
    results = {}
    for salt_name in ("salt1", "salt2"):
        salt = salts[salt_name]
        for scenario in ("RECOVERABLE", "PARITY_BLOCKED"):
            cell = rep["scenarios"][salt_name][scenario]
            entries = rep["raw"]["entries"][f"{salt_name}:{scenario}"]
            c.eq(verify_entries(entries, pubs), [], f"chain+signatures {salt_name}/{scenario}")
            c.eq(len(entries), cell["chain"]["entries"], f"entry count {salt_name}/{scenario}")
            # rebuild every candidate behaviour from the design, then follow the recorded order
            label_map = {f"prim:p{i}": PRIMITIVES[i] for i in range(6)}
            for t in TRACE:
                label_map[f"trace:{t[0]}/{t[1]}"] = word(list(t))
            for agent in AGENTS:
                for x in OWN[agent]:
                    for y in OWN[agent]:
                        label_map[f"mem:{agent}:{x}/{y}"] = word([x, y])
            avail = []
            for a in cell["available"]:
                c.ok(a["label"] in label_map, f"known label {a['label']}")
                avail.append((a["label"], label_map[a["label"]]))
            c.eq(len(avail), len(cell["available"]), f"available count {salt_name}/{scenario}")
            c.eq([sha(bytes(b)) for _l, b in avail], [a["behaviour_sha256"] for a in cell["available"]],
                 f"available hashes {salt_name}/{scenario}")
            d = bfs(avail, PRIMITIVES[LOST], DEPTH)
            c.eq(d["found"], cell["derivation"]["found"], f"derivation found {salt_name}/{scenario}")
            c.eq(d["depth"], cell["derivation"].get("depth"), f"derivation depth {salt_name}/{scenario}")
            c.eq(d["expanded"], cell["derivation_attempt"]["expanded"],
                 f"derivation expansions {salt_name}/{scenario}")
            if d["found"]:
                smap = dict(steps(avail))
                b = IDENTITY
                for label in d["word"]:
                    b = compose(smap[label], b)
                c.eq(b, PRIMITIVES[LOST], f"derivation exact {salt_name}/{scenario}")
                c.eq(cell["derivation"]["exact"], True, f"recorded exact {salt_name}/{scenario}")
            else:
                cl = closure([b for _l, b in avail])
                c.eq(len(cl), 2520, f"closure A7 {salt_name}/{scenario}")
                c.ok(PRIMITIVES[LOST] not in cl, "lost action not in closure")
                c.eq(cell["derivation"]["closure_size"], 2520, "recorded closure size")
            # primitive-only control
            po = bfs([(f"prim:p{i}", PRIMITIVES[i]) for i in SURVIVORS], PRIMITIVES[LOST], DEPTH)
            c.eq(po["found"], cell["primitive_only"]["found"],
                 f"primitive-only found {salt_name}/{scenario}")
            # capability from the revealed salt
            targets = gen_targets(salt, scenario)
            c.eq([list(t) for t in targets],
                 [t["behaviour"] for t in rep["raw"]["targets"][f"{salt_name}:{scenario}"]],
                 f"held-out targets {salt_name}/{scenario}")
            derived = bool(d["found"])
            arms = {
                "full": [(f"prim:p{i}", PRIMITIVES[i]) for i in range(6)],
                "lost": avail,
                "derive": avail + ([("derived:p4", PRIMITIVES[LOST])] if derived else []),
                "backup": [(f"prim:p{i}", PRIMITIVES[i]) for i in range(6)],
            }
            solved = {}
            for name, gens in arms.items():
                R = reachable(gens, DEPTH)
                solved[name] = sum(1 for t in targets if tuple(t) in R)
            c.eq(solved, cell["capability"]["solved"], f"capability {salt_name}/{scenario}")
            # governance
            c.eq(cell["chain"]["bad"], [], f"chain probe {salt_name}/{scenario}")
            c.eq(cell["tenant_probe"]["foreign_visible_to_us"], 0, "tenant isolation")
            c.eq(cell["tenant_probe"]["foreign_rows_in_table"], 1, "foreign row recorded")
            c.ok(all(not p["granted"] for p in cell["authority_probes"]), "no authority from memory")
            c.eq(cell["tamper_probe"]["detected"], True, "tamper detected")
            results[(salt_name, scenario)] = {"derivation": d, "solved": solved,
                                              "targets": targets}

    # hypotheses, recomputed
    h1 = all(results[(s, "RECOVERABLE")]["derivation"]["found"]
             and results[(s, "RECOVERABLE")]["solved"]["derive"] == SEALED
             for s in ("salt1", "salt2"))
    c.ok(h1, "H1 reconstructable restores ceiling")
    h2 = all((not rep["scenarios"][s]["RECOVERABLE"]["primitive_only"]["found"])
             and results[(s, "RECOVERABLE")]["derivation"]["depth"] <= DEPTH
             and any(not w.startswith("prim:") for w in results[(s, "RECOVERABLE")]["derivation"]["word"])
             for s in ("salt1", "salt2"))
    c.ok(h2, "H2 memory is the mechanism")
    h3 = all(results[(s, "RECOVERABLE")]["solved"]["derive"] == SEALED
             and results[(s, "RECOVERABLE")]["solved"]["derive"]
             - results[(s, "RECOVERABLE")]["solved"]["lost"] >= 8
             for s in ("salt1", "salt2"))
    c.ok(h3, "H3 capability recovered")
    h4 = all((not results[(s, "PARITY_BLOCKED")]["derivation"]["found"])
             and len(closure([b for _l, b in
                              [(f"prim:p{i}", PRIMITIVES[i]) for i in EVEN_PRIMS]])) == 2520
             for s in ("salt1", "salt2"))
    c.ok(h4, "H4 parity boundary")
    c.eq(rep["drill"]["distinct_pids"], 4, "drill distinct PIDs")
    c.eq(rep["drill"]["chain_valid"], True, "drill chain valid")
    c.eq(rep["verdict"], "DERIVATIONAL_SELF_REPAIR_SUPPORTED", "verdict")
    c.eq(rep["hypotheses"]["H1_reconstructable_restores_ceiling"]["verdict"], "SUPPORTED", "H1 verdict")
    c.eq(rep["hypotheses"]["H2_memory_is_the_mechanism"]["verdict"], "SUPPORTED", "H2 verdict")
    c.eq(rep["hypotheses"]["H3_capability_recovered"]["verdict"], "SUPPORTED", "H3 verdict")
    c.eq(rep["hypotheses"]["H4_parity_boundary_abstains"]["verdict"], "SUPPORTED", "H4 verdict")
    c.eq(rep["hypotheses"]["H5_no_false_recovery"]["verdict"], "SUPPORTED", "H5 verdict")
    c.eq(rep["hypotheses"]["H6_governance"]["verdict"], "SUPPORTED", "H6 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("E455-M VERIFICATION FAILED")
        for b in c.bad[:20]:
            print(" -", b)
        return 1
    print(f"E455-M VERIFIED {c.n}/{c.n} checks; {STATUS}")
    return 0


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