#!/usr/bin/env python3
"""EVG standalone auditor — replays the bounded campaign from the revealed salts, imports no CAIN code.

The auditor rebuilds the permutation world, the 64 macros, the partition, every generation's
proposal stream (including the insider's false claims), the library under each of the eight eviction
policies, every checkpoint, every governed-memory entry (signature and hash chain) and every
hypothesis.

Usage: python3 verify_evg_offline.py <bundle-dir>
"""
from __future__ import annotations

import hashlib
import itertools
import json
import sys
from pathlib import Path

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

N = 64
PRIMS = 8
CAP = 30
UNBOUNDED_CAP = 64
GENERATIONS = 4
USEFUL_PER_GEN = 12
DISTRACTORS_PER_GEN = 4
INSIDER_PER_GEN = 2
TASKS_PER_GEN = 8
AGENTS = ("A0", "A1", "A2", "A3")
INSIDER = "mallory"
VERIFIER = "verifier"
MACROS = tuple(itertools.product(range(PRIMS), range(PRIMS)))
ARMS = ("UNBOUNDED", "LRU", "LFU", "RANDOM", "REGRESSION", "REGRESSION_STRICT", "FREEZE", "INSIDER_TRUST")
TENANT = "cain42-evg"
SEED = "evg"


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b).hexdigest()


def u(s):
    return int.from_bytes(hashlib.sha256(s.encode()).digest()[:8], "big") / 2 ** 64


def macro_key(m):
    return f"{m[0]}:{m[1]}"


def perm(salt, i):
    out, seen = [], set()
    for x in range(N):
        y = int(hashlib.sha256(f"evg-perm|{salt}|{i}|{x}".encode()).hexdigest()[:16], 16) % N
        while y in seen:
            y = (y + 1) % N
        seen.add(y)
        out.append(y)
    return tuple(out)


def base(salt):
    return [perm(salt, i) for i in range(PRIMS)]


def behaviour(salt, m):
    p = base(salt)
    a, b = p[m[0]], p[m[1]]
    return tuple(a[b[x]] for x in range(N))


def partition(salt):
    order = sorted(MACROS, key=lambda m: (sha(f"evg-order|{salt}|{macro_key(m)}".encode()), m))
    useful = [order[i * USEFUL_PER_GEN:(i + 1) * USEFUL_PER_GEN] for i in range(GENERATIONS)]
    return useful, order[GENERATIONS * USEFUL_PER_GEN:]


def distractors(salt, g):
    useful, rest = partition(salt)
    if not rest:
        rest = sorted(MACROS, key=lambda m: sha(f"evg-d|{salt}|{g}|{macro_key(m)}".encode()))
    start = (g * DISTRACTORS_PER_GEN) % len(rest)
    return [rest[(start + k) % len(rest)] for k in range(DISTRACTORS_PER_GEN)]


def stream(salt, g):
    useful, _ = partition(salt)
    honest = [{"by": AGENTS[i % len(AGENTS)], "macro": m, "claimed": behaviour(salt, m), "insider": False}
              for i, m in enumerate(useful[g] + distractors(salt, g))]
    bad = []
    for k in range(INSIDER_PER_GEN):
        m = MACROS[(int(hashlib.sha256(f"evg-bad|{salt}|{g}|{k}".encode()).hexdigest()[:8], 16)) % len(MACROS)]
        fake = tuple((x * 3 + 7 + k) % N for x in range(N))
        bad.append({"by": INSIDER, "macro": m, "claimed": fake, "insider": True})
    return honest + bad


def task_macros(salt, g, j):
    useful, _ = partition(salt)
    s = useful[g - 1]
    i1 = (j * 5 + 1) % len(s)
    i2 = (j * 7 + 3) % len(s)
    if i2 == i1:
        i2 = (i2 + 1) % len(s)
    return s[i1], s[i2]


def solvable(lib, salt, g, j):
    m1, m2 = task_macros(salt, g, j)
    return behaviour(salt, m1) in lib and behaviour(salt, m2) in lib


def usage(salt, g, j):
    m1, m2 = task_macros(salt, g, j)
    return [behaviour(salt, m1), behaviour(salt, m2)]


class Chain:
    def __init__(self):
        self.entries, self.prev = [], ""
        self.pubs = {a: self.pub(a) for a in [*AGENTS, INSIDER, VERIFIER]}

    @staticmethod
    def key(agent):
        return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{agent}".encode()).digest())

    def pub(self, agent):
        return self.key(agent).public_key().public_bytes(
            serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()

    def append(self, agent, kind, key, value):
        seq = len(self.entries) + 1
        n = sha(canon({"agent": agent, "kind": kind, "key": key, "value": value}))[:16]
        payload = {"seq": seq, "tenant": TENANT, "agent": agent, "kind": kind, "key": key,
                   "value": value, "prev": self.prev, "nonce": n, "created_at": seq / 1000.0,
                   "grants_authority": False, "executable": False}
        body = canon(payload)
        sig = self.key(agent).sign(body).hex()
        h = sha(self.prev.encode() + body + bytes.fromhex(sig))
        self.entries.append({**payload, "hash": h, "sig": sig})
        self.prev = h

    def head(self):
        kinds = {}
        for x in self.entries:
            kinds[x["kind"]] = kinds.get(x["kind"], 0) + 1
        return {"tenant": TENANT, "count": len(self.entries), "head": self.prev,
                "kinds": kinds, "agents": sorted({x["agent"] for x in self.entries})}

    def verify(self):
        prev = ""
        for e in self.entries:
            body = canon({k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                            "nonce", "created_at", "grants_authority", "executable")})
            if e["prev"] != prev:
                return False
            if sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) != e["hash"]:
                return False
            if e["nonce"] != sha(canon({"agent": e["agent"], "kind": e["kind"], "key": e["key"],
                                        "value": e["value"]}))[:16]:
                return False
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(self.pubs[e["agent"]])).verify(
                    bytes.fromhex(e["sig"]), body)
            except Exception:
                return False
            prev = e["hash"]
        return True


class Library:
    def __init__(self):
        self.entries, self.clock = {}, 0

    def cap(self, arm):
        return UNBOUNDED_CAP if arm == "UNBOUNDED" else CAP

    def add(self, beh, macro, g, idx):
        self.entries[beh] = {"behaviour": beh, "macro": list(macro), "admitted_at": self.clock,
                             "last_used": self.clock, "uses": 0, "gen": g, "idx": idx}

    def touch(self, beh):
        e = self.entries.get(beh)
        if e is not None:
            e["last_used"] = self.clock
            e["uses"] += 1

    def retained(self, salt, upto):
        return sum(1 for g in range(1, upto + 1) for j in range(TASKS_PER_GEN) if solvable(self.entries, salt, g, j))


def victim(arm, lib, salt, cand_beh, g, idx):
    keys = list(lib.entries)
    if arm == "LRU":
        v = min(keys, key=lambda b: (lib.entries[b]["last_used"], lib.entries[b]["admitted_at"], b))
        return v, "EVICT"
    if arm == "LFU":
        v = min(keys, key=lambda b: (lib.entries[b]["uses"], lib.entries[b]["last_used"], b))
        return v, "EVICT"
    if arm == "RANDOM":
        v = min(keys, key=lambda b: (hashlib.sha256(f"evg-r|{idx}|{b}".encode()).hexdigest(), b))
        return v, "EVICT"
    if arm in ("REGRESSION", "REGRESSION_STRICT"):
        upto = g + 1
        cur = lib.retained(salt, upto) if upto >= 1 else 0
        best = None
        for v in keys:
            saved = lib.entries.pop(v)
            lib.entries[cand_beh] = {"behaviour": cand_beh, "macro": None, "admitted_at": lib.clock,
                                     "last_used": lib.clock, "uses": 0, "gen": g, "idx": idx}
            score = lib.retained(salt, upto) if upto >= 1 else 0
            lib.entries.pop(cand_beh)
            lib.entries[v] = saved
            key = (score, -saved["last_used"], v)
            if best is None or key > best[0]:
                best = (key, v, score)
        if best is None:
            return None, "REJECT_FULL"
        _k, v, score = best
        if arm == "REGRESSION_STRICT" and upto >= 1 and score < cur:
            return None, "REJECT_PROTECTED"
        return v, "EVICT"
    return None, "REJECT_FULL"


def run_arm(salt, arm, chain):
    lib = Library()
    log, checkpoints = [], []
    for g in range(GENERATIONS):
        for idx, prop in enumerate(stream(salt, g)):
            true_beh = behaviour(salt, prop["macro"])
            claimed = tuple(prop["claimed"])
            key = f"g{g}:{idx}:{macro_key(prop['macro'])}"
            chain.append(prop["by"], "proposal", key,
                         {"gen": g, "index": idx, "macro": list(prop["macro"]),
                          "claimed": list(claimed), "insider": prop["insider"]})
            if arm != "INSIDER_TRUST" and claimed != true_beh:
                decision = "REJECT_INVALID"
                chain.append(VERIFIER, "verification", key,
                             {"gen": g, "index": idx, "recomputed": list(true_beh),
                              "matches_claim": False, "decision": decision})
                log.append({"gen": g, "idx": idx, "macro": list(prop["macro"]), "insider": prop["insider"],
                            "decision": decision, "victim": None, "behaviour": list(true_beh)})
                continue
            beh = true_beh if arm != "INSIDER_TRUST" else claimed
            if beh in lib.entries:
                decision, v = "DUPLICATE", None
            elif len(lib.entries) < lib.cap(arm):
                decision, v = "ADMIT", None
                lib.add(beh, prop["macro"], g, idx)
            else:
                v, decision = victim(arm, lib, salt, beh, g, idx)
                if v is not None:
                    lib.entries.pop(v)
                    lib.add(beh, prop["macro"], g, idx)
            chain.append(VERIFIER, "verification", key,
                         {"gen": g, "index": idx, "recomputed": list(true_beh),
                          "matches_claim": claimed == true_beh, "decision": decision,
                          "victim": list(v) if v is not None else None, "library": len(lib.entries)})
            log.append({"gen": g, "idx": idx, "macro": list(prop["macro"]), "insider": prop["insider"],
                        "decision": decision, "victim": list(v) if v is not None else None,
                        "behaviour": list(beh)})
        lib.clock += 1
        per_gen = {}
        for gg in range(1, GENERATIONS + 1):
            n = 0
            for j in range(TASKS_PER_GEN):
                if solvable(lib.entries, salt, gg, j):
                    n += 1
                    for beh in usage(salt, gg, j):
                        lib.touch(beh)
            per_gen[str(gg)] = n
        checkpoints.append({"after_generation": g + 1, "solved": per_gen,
                            "total": sum(per_gen.values()), "library": len(lib.entries)})
        chain.append(VERIFIER, "checkpoint", f"ckpt:{g + 1}",
                     {"after_generation": g + 1, "solved": per_gen, "library": len(lib.entries)})
    final = checkpoints[-1]
    return {"log": log, "checkpoints": checkpoints, "final_total": final["total"],
            "final_per_gen": final["solved"], "library": final["library"], "memory": chain.head()}


def counts(log):
    return {"evict": sum(1 for x in log if x["decision"] == "EVICT"),
            "invalid": sum(1 for x in log if x["decision"] == "REJECT_INVALID"),
            "protected": sum(1 for x in log if x["decision"] == "REJECT_PROTECTED"),
            "full": sum(1 for x in log if x["decision"] == "REJECT_FULL"),
            "duplicate": sum(1 for x in log if x["decision"] == "DUPLICATE"),
            "admit": sum(1 for x in log if x["decision"] == "ADMIT")}


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"")


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(label, ok):
        checks.append((label, bool(ok)))

    man = json.loads((d / "EVG_MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey as _Pub
    try:
        _Pub.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
        ck("manifest:signature", True)
    except Exception:
        ck("manifest:signature", False)
    files = sorted(p for p in d.rglob("*") if p.is_file()
                   and str(p.relative_to(d)) not in {"EVG_MANIFEST.json", "EVG_SIGNED_BODY.json",
                                                     "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                                                     "EVG_OMEGA_SEAL.json", "EVG_PUBKEY.pem",
                                                     "EVG_VERIFICATION_RESULTS.json", "EVG_TAMPER_RESULTS.json"}
                   and "__pycache__" not in p.parts)
    ck("manifest:files", {str(p.relative_to(d)): sha(p.read_bytes()) for p in files} == man["files"])
    ck("manifest:merkle", merkle(files) == man["merkle_root"])

    pre = json.loads((d / "EVG_PREREGISTRATION.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    ck("salts:commitment", {k: sha(v.encode()) for k, v in salts.items()} == pre["salts_commitment"])
    report = json.loads((d / "EVG_RUN_REPORT.json").read_text())
    ck("rows:sha256", report.get("rows_sha256") == sha((d / "EVG_ROWS.json").read_bytes()))
    ck("constants", report["capacity"] == CAP and report["generations"] == GENERATIONS
       and report["tasks_per_generation"] == TASKS_PER_GEN)

    replay = {}
    for salt in ("salt1", "salt2"):
        sv = salts[salt]
        for arm in ARMS:
            chain = Chain()
            r = run_arm(sv, arm, chain)
            m = report["measurements"][salt][arm]
            ck(f"{salt}:{arm}:final", r["final_total"] == m["final"])
            ck(f"{salt}:{arm}:per_gen", r["final_per_gen"] == m["per_gen"])
            ck(f"{salt}:{arm}:checkpoints", r["checkpoints"] == m["checkpoints"])
            ck(f"{salt}:{arm}:counts", counts(r["log"]) == m["counts"])
            ck(f"{salt}:{arm}:library", r["library"] == m["library"])
            ck(f"{salt}:{arm}:memory", r["memory"]["count"] == m["memory_entries"] and chain.verify())
            replay.setdefault(salt, {})[arm] = r

    H = report["hypotheses"]
    for s in ("salt1", "salt2"):
        def fin(arm):
            return replay[s][arm]["final_total"]
        def gen(arm, g):
            return replay[s][arm]["final_per_gen"][str(g)]
        d1 = H["H1_bounded_memory_forgets"]["detail"][s]
        ck(f"H1:{s}:detail", d1["lru"] == fin("LRU") and d1["unbounded"] == fin("UNBOUNDED")
           and d1["delta"] == fin("LRU") - fin("UNBOUNDED"))
        ck(f"H1:{s}", (fin("LRU") < fin("UNBOUNDED")) == d1["ok"])
        d2 = H["H2_gate_beats_recency_on_accumulated_capability"]["detail"][s]
        ck(f"H2:{s}:detail", d2["regression"] == fin("REGRESSION") and d2["lru"] == fin("LRU")
           and d2["delta"] == fin("REGRESSION") - fin("LRU"))
        ck(f"H2:{s}", (fin("REGRESSION") > fin("LRU")) == d2["ok"])
        d3 = H["H3_gate_retains_old_generations"]["detail"][s]
        ck(f"H3:{s}:detail", d3["regression_old"] == gen("REGRESSION", 1) + gen("REGRESSION", 2)
           and d3["lru_old"] == gen("LRU", 1) + gen("LRU", 2))
        ck(f"H3:{s}", ((gen("REGRESSION", 1) + gen("REGRESSION", 2)) > (gen("LRU", 1) + gen("LRU", 2))) == d3["ok"])
        d4 = H["H4_the_frontier_is_the_price"]["detail"][s]
        ck(f"H4:{s}:detail", d4["regression_new"] == gen("REGRESSION", 4) and d4["lru_new"] == gen("LRU", 4)
           and d4["delta"] == gen("REGRESSION", 4) - gen("LRU", 4))
        ck(f"H4:{s}", (gen("REGRESSION", 4) < gen("LRU", 4)) == d4["ok"])
        d5 = H["H5_freezing_stagnates"]["detail"][s]
        ck(f"H5:{s}:detail", d5["freeze"] == fin("FREEZE") and d5["regression"] == fin("REGRESSION"))
        ck(f"H5:{s}", (fin("FREEZE") < fin("REGRESSION")) == d5["ok"])
        d6 = H["H6_unverified_admission_fills_the_store"]["detail"][s]
        ck(f"H6:{s}:detail", d6["insider_trust"] == fin("INSIDER_TRUST") and d6["regression"] == fin("REGRESSION"))
        ck(f"H6:{s}", (fin("INSIDER_TRUST") < fin("REGRESSION")) == d6["ok"])
        rep = H["H8_reported_context"]["detail"][s]
        ck(f"H8:{s}", all(rep[a]["final"] == replay[s][a]["final_total"] for a in ARMS))

    core = all(H[k].get("ok") for k in ("H1_bounded_memory_forgets",
                                        "H2_gate_beats_recency_on_accumulated_capability",
                                        "H3_gate_retains_old_generations", "H4_the_frontier_is_the_price",
                                        "H5_freezing_stagnates", "H6_unverified_admission_fills_the_store",
                                        "H7_integrity_and_no_authority"))
    verdict = "BOUNDED_MEMORY_EVICTION_SUPPORTED" if core else "NOT_SUPPORTED"
    ck("verdict", verdict == report["verdict"])
    ck("no_model_calls", report.get("model_calls") == 0)

    bad = [k for k, ok in checks if not ok]
    print(f"EVG auditor: {len(checks) - len(bad)}/{len(checks)} checks passed")
    if bad:
        print("FAILED:", ", ".join(bad))
        return 1
    print(f"VERDICT {verdict}")
    return 0


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