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

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**:
the available even content, the per-task bounded search, the certified agreement sets, the parity
proof, every arm, the hypotheses and the verdict.

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

import hashlib
import json
import random
import sys
from collections import deque
from itertools import combinations
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 = "e457m"
AGENTS = ["atlas", "borealis", "cetus", "draco"]
DEPARTED = "cetus"
POISON = "mallory"
OWN = {"atlas": [0, 1], "borealis": [2, 3], "cetus": [4, 5], "draco": [1, 5]}
PUBLIC_PRIM = 1
LOST = 4
LEVELS = [2, 3, 4, 5, 6]
PER_LEVEL = 7
DEPTH = 6
TENANT = "cain42-e457m"
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 += [b, 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 agreement(r):
    return sum(1 for i in range(N) if r[i] == PRIMITIVES[LOST][i])


def agree_on(r, S):
    return all(r[i] == PRIMITIVES[LOST][i] for i in S)


def agreement_set(r):
    return [i for i in range(N) if r[i] == PRIMITIVES[LOST][i]]


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


def one_scope(gens, depth=DEPTH):
    st = steps(gens)
    seen = {IDENTITY}
    frontier = [(IDENTITY, [])]
    best = {"word": [], "behaviour": IDENTITY, "agreement": agreement(IDENTITY), "depth": 0}
    expanded = 0
    for d in range(1, depth + 1):
        nxt = []
        for b, prog in frontier:
            for label, g in st:
                expanded += 1
                nb = compose(g, b)
                if nb in seen:
                    continue
                seen.add(nb)
                a = agreement(nb)
                if a > best["agreement"] or (a == best["agreement"] and not best["word"]):
                    best = {"word": prog + [label], "behaviour": nb, "agreement": a, "depth": d}
                nxt.append((nb, prog + [label]))
        frontier = nxt
        if not frontier:
            break
    b = best["behaviour"]
    best["agreement_set"] = agreement_set(b)
    best["expanded"] = expanded
    return best


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


def gen_tasks(salt):
    out = []
    for k in LEVELS:
        r = rng(salt, "subsets", k)
        subs = list(combinations(range(N), k))
        r.shuffle(subs)
        for i in range(PER_LEVEL):
            out.append({"id": f"k{k}-t{i:02d}", "k": k, "S": list(subs[i])})
    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 / "E457M_MANIFEST.json").read_text())
    c.eq(man["schema"], "cain42.e457m.manifest.v1", "manifest schema")
    c.eq(man["evolution"], "E457-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}")
    files = [root / n for n in man["files"]]
    c.eq(merkle(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 / "E457M_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    frz = json.loads((root / "E457M_PREREGISTRATION_FREEZE.json").read_text())
    pre = json.loads((root / "E457M_PREREGISTRATION.json").read_text())
    c.eq(frz["preregistration_sha256"], sha((root / "E457M_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 AGENTS + [POISON]}
    solved_all = {}
    for name in ("salt1", "salt2"):
        salt = salts[name]
        cell = rep["scenarios"][name]
        entries = rep["raw"]["entries"][name]
        c.eq(verify_entries(entries, pubs), [], f"chain+signatures {name}")
        c.eq(len(entries), cell["chain"]["entries"], f"entry count {name}")
        # available content
        gens = [(f"prim:p{PUBLIC_PRIM}", PRIMITIVES[PUBLIC_PRIM])]
        for agent in AGENTS:
            if agent == DEPARTED:
                continue
            for x in OWN[agent]:
                for y in OWN[agent]:
                    if parity(PRIMITIVES[x]) == 0 and parity(PRIMITIVES[y]) == 0:
                        gens.append((f"mem:{agent}:{x}/{y}", word([x, y])))
        seen_b, avail = set(), []
        for label, b in gens:
            if b in seen_b:
                continue
            seen_b.add(b)
            avail.append((label, b))
        c.eq([sha(bytes(b)) for _l, b in avail], [a["behaviour_sha256"] for a in cell["available"]],
             f"available hashes {name}")
        cl = closure([b for _l, b in avail])
        c.eq(len(cl), 2520, f"closure A7 {name}")
        c.ok(all(parity(x) == 0 for x in cl), f"closure all even {name}")
        # exact impossible
        ex = solve_subset(avail, list(range(N)), DEPTH)
        c.eq(ex["found"], cell["exact_found"], f"exact found {name}")
        c.eq(cell["exact_found"], False, f"exact impossible {name}")
        # one scope
        one = one_scope(avail, DEPTH)
        c.eq(one["agreement"], cell["one_scope"]["agreement"], f"one-scope agreement {name}")
        c.eq(one["word"], cell["one_scope"]["word"], f"one-scope word {name}")
        c.eq(one["agreement_set"], cell["one_scope"]["agreement_set"], f"one-scope set {name}")
        c.eq(sha(bytes(one["behaviour"])), cell["one_scope"]["behaviour_sha256"],
             f"one-scope behaviour {name}")
        # tasks
        tasks = gen_tasks(salt)
        rec = rep["raw"]["tasks"][name]
        c.eq([t["S"] for t in tasks], [t["S"] for t in rec], f"task subsets {name}")
        prim = [(f"prim:p{PUBLIC_PRIM}", PRIMITIVES[PUBLIC_PRIM])]
        solved = {a: {k: 0 for k in LEVELS} for a in
                  ("lost", "synth", "unscoped", "exact", "primitive_only", "oracle")}
        over = 0
        for t, r in zip(tasks, rec):
            s = solve_subset(avail, t["S"], DEPTH)
            p = solve_subset(prim, t["S"], DEPTH)
            c.eq(s["found"], r["synth"]["found"], f"synth found {name} {t['id']}")
            c.eq(s["word"], r["synth"]["word"], f"synth word {name} {t['id']}")
            c.eq(s["agreement"], r["synth"]["agreement"], f"synth agreement {name} {t['id']}")
            if s["found"]:
                c.ok(set(t["S"]) <= set(s["agreement_set"]), f"scope contains task {name} {t['id']}")
            c.eq(p["found"], r["primitive_only"]["found"], f"primitive found {name} {t['id']}")
            solved["synth"][t["k"]] += int(s["found"])
            solved["primitive_only"][t["k"]] += int(p["found"])
            un = agree_on(one["behaviour"], t["S"])
            solved["unscoped"][t["k"]] += int(un)
            solved["oracle"][t["k"]] += int(t["k"] <= 5)
            solved["lost"][t["k"]] += 0
            solved["exact"][t["k"]] += 0
            over += 0 if un else 1
        c.eq({a: {str(k): v for k, v in d.items()} for a, d in solved.items()},
             cell["solved"], f"arm totals {name}")
        c.eq(over, cell["unscoped_overclaims"], f"unscoped overclaims {name}")
        # parity proof
        six = list(combinations(range(N), 6))
        agree = sum(1 for S in six for b in cl if agree_on(b, S))
        c.eq(agree, 0, f"no even agreement on a 6-subset {name}")
        c.eq(cell["parity_proof"]["even_agreements"], 0, f"recorded parity proof {name}")
        # governance
        c.eq(cell["chain"]["bad"], [], f"chain probe {name}")
        c.eq(cell["tenant_probe"]["foreign_visible_to_us"], 0, "tenant isolation")
        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")
        solved_all[name] = solved

    def tot(s, arm, levels=None):
        levels = levels or LEVELS
        return sum(solved_all[s][arm][k] for k in levels)

    h1 = all(tot(s, "synth", [2, 3, 4]) == 3 * PER_LEVEL and tot(s, "synth", [5]) >= PER_LEVEL - 1
             and tot(s, "synth", [6]) == 0 for s in ("salt1", "salt2"))
    c.ok(h1, "H1 scope frontier")
    h2 = all(tot(s, "primitive_only", [3, 4, 5]) * 2 <= tot(s, "synth", [3, 4, 5])
             for s in ("salt1", "salt2"))
    c.ok(h2, "H2 memory is the mechanism")
    h3 = all(rep["scenarios"][s]["synth_overclaims"] == 0
             and rep["scenarios"][s]["unscoped_overclaims"] >= 1 for s in ("salt1", "salt2"))
    c.ok(h3, "H3 scope certificate")
    h4 = all(not rep["scenarios"][s]["exact_found"]
             and tot(s, "exact") == 0
             and any(e["kind"] == "abstention" for e in rep["raw"]["entries"][s])
             for s in ("salt1", "salt2"))
    c.ok(h4, "H4 exact impossible")
    h5 = all(tot(s, "synth") >= 0.9 * tot(s, "oracle") for s in ("salt1", "salt2"))
    c.ok(h5, "H5 capability restored")
    c.eq(rep["drill"]["distinct_pids"], 4, "drill distinct PIDs")
    c.eq(rep["drill"]["chain_valid"], True, "drill chain valid")
    c.eq(rep["verdict"], "SCOPE_CERTIFIED_REPAIR_SUPPORTED", "verdict")
    for k in ("H1_scope_frontier", "H2_memory_is_the_mechanism", "H3_scope_certificate",
              "H4_exact_impossible", "H5_capability_restored", "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("E457-M VERIFICATION FAILED")
        for b in c.bad[:20]:
            print(" -", b)
        return 1
    print(f"E457-M VERIFIED {c.n}/{c.n} checks; {STATUS}")
    return 0


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