#!/usr/bin/env python3
"""EVD standalone auditor — re-derives the whole cache study from the revealed salts. No CAIN imports.

Rebuilds the 192-row worlds, the 12 designs and the 96 requests of every campaign, replays all five
arms and both accounting modes, recomputes every promotion, every aggregate and every hypothesis, then
verifies the signed manifest, the file hashes and Merkle root, the salt commitments, and every Ed25519
signature and SHA-256 link of the exported governed memory.

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

import hashlib
import json
import math
import sys
from pathlib import Path

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

ROWS, DESIGNS, DESIGN_ROWS = 192, 12, 16
AGENTS = [f"a{i}" for i in range(8)]
ROUNDS, BUDGET, CAMPAIGNS = 16, 128, 200
Z99, ALPHA = 2.3263478740408408, 0.01
WORLDS = ("null", "alt")
SERVED_ARMS = ("naive_cache", "ess_cache", "naive_nocache", "ess_nocache")
MEMORY_ARMS = SERVED_ARMS
ARMS = SERVED_ARMS + ("oracle",)
CACHE = {"naive_cache": True, "ess_cache": True, "naive_nocache": False, "ess_nocache": False}
ACCOUNTING = {"naive_cache": "naive", "ess_cache": "ess", "naive_nocache": "naive", "ess_nocache": "ess"}
TENANT, SEED = "cain42-evd", "evd"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"


CANON_HYP = {
    "H1_cache_buys_distinct_experiments": "at 128 labels the cache observes at least 1.2x more distinct rows than a no-cache colony, both salts",
    "H2_naive_cache_inflates": "counting repeated reports as independent pushes the null false-promotion rate above 5% (>5x alpha), both salts",
    "H3_ess_holds_alpha": "counting distinct rows only keeps the null false-promotion rate at or below 1.5%, both salts",
    "H4_cache_buys_power": "at the same 128-label budget, distinct-row accounting plus the cache has at least 5 points more power than no cache, both salts",
    "H5_integrity_and_no_authority": "every governed memory verifies its chain and signatures, refuses a replayed nonce, detects a tampered entry, and refuses authority from memory",
    "H6_external_review": "no external reviewer (BLOCKED)",
}


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


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


def design_rows(d):
    return list(range(d * DESIGN_ROWS, (d + 1) * DESIGN_ROWS))


def design_for(salt, world, campaign, agent, rnd):
    h = int(hashlib.sha256(f"{salt}|{world}|c{campaign}|a{agent}|r{rnd}".encode()).hexdigest()[:8], 16)
    if (h >> 8) % 10 < 7:
        return (2 * agent + rnd) % DESIGNS
    return h % DESIGNS


def world_rows(salt, world, campaign):
    m = 96 if world == "null" else 116
    order = sorted(range(ROWS), key=lambda r: hashlib.sha256(
        f"{salt}|{world}|c{campaign}|perm|{r}".encode()).hexdigest())
    bits = [0] * ROWS
    for r in order[:m]:
        bits[r] = 1
    return bits


def wilson_lower(k, n, z=Z99):
    if n <= 0:
        return 0.0
    p = k / n
    denom = 1.0 + z * z / n
    centre = p + z * z / (2.0 * n)
    margin = z * math.sqrt(max(p * (1.0 - p) / n + z * z / (4.0 * n * n), 0.0))
    return (centre - margin) / denom


def run_campaign(salt, world, arm, campaign):
    bits = world_rows(salt, world, campaign)
    paid, log, refused, left = {}, [], 0, BUDGET
    for k in range(ROUNDS):
        for i, agent in enumerate(AGENTS):
            d = design_for(salt, world, campaign, i, k)
            rows = design_rows(d)
            need = [r for r in rows if r not in paid] if CACHE.get(arm, True) else list(rows)
            if len(need) > left:
                refused += 1
                continue
            for r in need:
                paid[r] = bits[r]
            left -= len(need)
            log.append({"agent": agent, "design": d, "fresh": need,
                        "cached": [r for r in rows if r not in need], "labels": len(need)})
    mode = ACCOUNTING.get(arm, "oracle")
    if mode == "naive":
        n = sum(len(design_rows(x["design"])) for x in log)
        k_ok = sum(sum(paid[r] for r in design_rows(x["design"])) for x in log)
    else:
        n = len(paid)
        k_ok = sum(paid.values())
    promote = (wilson_lower(k_ok, n) > 0.5) if arm != "oracle" else (world == "alt")
    return {"arm": arm, "world": world, "served": len(log), "refused": refused,
            "labels": sum(x["labels"] for x in log), "distinct_designs": len({x["design"] for x in log}),
            "distinct_rows": len(paid), "accounting": mode, "n": n, "k": k_ok,
            "lower": round(wilson_lower(k_ok, n), 6), "promote": bool(promote), "reads": log}


def main():
    if len(sys.argv) < 2:
        print("usage: verify_evd_offline.py <bundle-dir>")
        return 2
    d = Path(sys.argv[1])
    checks, fails = [], []

    def ck(n, ok):
        checks.append(n)
        if not ok:
            fails.append(n)

    man = json.loads((d / "MANIFEST.json").read_text())
    body = canon({k: v for k, v in man.items() if k != "signature"})
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), body)
        ck("manifest signature", True)
    except Exception:
        ck("manifest signature", False)
    fs = sorted(p for p in d.rglob("*") if p.is_file()
                and p.name not in ("MANIFEST.json", "EVD_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                                   "EVD_OMEGA_SEAL.json", "EVD_PUBKEY.pem", "EVD_SIGNED_BODY.json")
                and "__pycache__" not in p.parts)
    hashed = {str(p.relative_to(d)): sha(p.read_bytes()) for p in fs}
    ck("file hashes", all(man["files"].get(k) == v for k, v in hashed.items()))
    ck("no unlisted file", set(man["files"]) == set(hashed))
    l = sorted(man["files"].values())
    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)]
    ck("merkle root", (l[0] if l else sha(b"")) == man["merkle_root"])
    ck("engine withheld", man.get("engine_withheld") is True)
    ck("external review not claimed", man.get("external_review") == "NOT_OBTAINED")

    pre = json.loads((d / "EVD_PREREGISTRATION.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    ck("salt commitment", {k: sha(v.encode()) for k, v in sal.items()} == pre["salts_commitment"])
    ck("status line", pre["status"] == STATUS)
    ck("prereg hypotheses", pre["hypotheses"] == CANON_HYP)

    rep = json.loads((d / "EVD_RUN_REPORT.json").read_text())
    rows_file = json.loads((d / "EVD_ROWS.json").read_text())
    mem = json.loads((d / "EVD_MEMORY.json").read_text())

    sims = {s: {a: {w: [run_campaign(sal[s], w, a, i) for i in range(CAMPAIGNS)] for w in WORLDS}
                for a in ARMS} for s in sal}

    for s in sal:
        for a in ARMS:
            for w in WORLDS:
                got = rows_file[s][a][w]
                sim = sims[s][a][w]
                ck(f"rows {s}:{a}:{w}", len(got) == len(sim))
                bad = 0
                for g, r in zip(got, sim):
                    for key in ("served", "refused", "labels", "distinct_designs", "distinct_rows",
                                "accounting", "n", "k", "promote", "lower"):
                        if g.get(key) != r.get(key):
                            bad += 1
                            break
                ck(f"values {s}:{a}:{w}", bad == 0)

    def rate(s, a, w):
        return sum(1 for c in sims[s][a][w] if c["promote"]) / CAMPAIGNS

    def mean(s, a, w, key):
        return sum(c[key] for c in sims[s][a][w]) / CAMPAIGNS

    H = rep["hypotheses"]
    ck("H1", all(mean(s, "ess_cache", "null", "distinct_rows")
                 >= 1.2 * mean(s, "ess_nocache", "null", "distinct_rows") for s in sal)
       and H["H1_cache_buys_distinct_experiments"]["verdict"] == "SUPPORTED")
    ck("H2", all(rate(s, "naive_cache", "null") > 0.05 for s in sal)
       and H["H2_naive_cache_inflates"]["verdict"] == "SUPPORTED")
    ck("H3", all(rate(s, "ess_cache", "null") <= 0.015 for s in sal)
       and H["H3_ess_holds_alpha"]["verdict"] == "SUPPORTED")
    ck("H4", all(rate(s, "ess_cache", "alt") >= rate(s, "ess_nocache", "alt") + 0.05 for s in sal)
       and H["H4_cache_buys_power"]["verdict"] == "SUPPORTED")
    h5 = H["H5_integrity_and_no_authority"]["detail"]
    ck("H5", all(h5[f"{s}:{a}"]["chain_and_signatures"] and h5[f"{s}:{a}"]["replay_refused"]
                 and h5[f"{s}:{a}"]["tamper_detected"] and h5[f"{s}:{a}"]["authority_from_memory_refused"]
                 and h5[f"{s}:{a}"]["authority_flag_false_everywhere"]
                 for s in sal for a in MEMORY_ARMS)
       and H["H5_integrity_and_no_authority"]["verdict"] == "SUPPORTED")
    core = all(H[k]["verdict"] == "SUPPORTED" for k in
               ("H1_cache_buys_distinct_experiments", "H2_naive_cache_inflates", "H3_ess_holds_alpha",
                "H4_cache_buys_power", "H5_integrity_and_no_authority"))
    ck("verdict", rep["verdict"] == ("CACHE_NOT_A_WITNESS_SUPPORTED" if core else "NOT_SUPPORTED"))
    ck("summary", all(rep["summary"][s][a][w] == {
        "promotion_rate": round(rate(s, a, w), 4),
        "mean_n": round(mean(s, a, w, "n"), 4),
        "mean_served": round(mean(s, a, w, "served"), 4),
        "mean_labels": round(mean(s, a, w, "labels"), 4),
        "mean_designs": round(mean(s, a, w, "distinct_designs"), 4),
        "mean_rows": round(mean(s, a, w, "distinct_rows"), 4)}
        for s in sal for a in ARMS for w in WORLDS))
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("arm set", tuple(rep["design"]["arms"]) == ARMS)
    ck("design declared", (rep["design"]["rows"], rep["design"]["designs"], rep["design"]["rounds"],
                           rep["design"]["budget_per_campaign"], rep["design"]["campaigns"])
       == (ROWS, DESIGNS, ROUNDS, BUDGET, CAMPAIGNS))

    def kp(a):
        return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())

    def nce(a, kind, key, value):
        return sha(canon({"agent": a, "kind": kind, "key": key, "value": value}))[:16]

    total = 0
    for s in mem:
        for a, entries in mem[s].items():
            prev, bad = "", 0
            for e in entries:
                b = canon({k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                             "nonce", "created_at", "grants_authority", "executable")})
                ok = (e["prev"] == prev and e["tenant"] == TENANT
                      and sha(e["prev"].encode() + b + bytes.fromhex(e["sig"])) == e["hash"]
                      and e["nonce"] == nce(e["agent"], e["kind"], e["key"], e["value"])
                      and e["grants_authority"] is False and e["executable"] is False)
                if ok:
                    try:
                        Ed25519PublicKey.from_public_bytes(
                            kp(e["agent"]).public_key().public_bytes(
                                serialization.Encoding.Raw, serialization.PublicFormat.Raw)
                        ).verify(bytes.fromhex(e["sig"]), b)
                    except Exception:
                        ok = False
                bad += 0 if ok else 1
                prev = e["hash"]
            total += len(entries)
            ck(f"memory chain {s}:{a}", bad == 0)
            ck(f"memory count {s}:{a}", len(entries) == 2 * CAMPAIGNS)
            for w in WORLDS:
                ck(f"memory values {s}:{a}:{w}",
                   all(entries[(0 if w == "null" else CAMPAIGNS) + i]["value"]["promote"]
                       == sims[s][a][w][i]["promote"]
                       and entries[(0 if w == "null" else CAMPAIGNS) + i]["value"]["n"] == sims[s][a][w][i]["n"]
                       and entries[(0 if w == "null" else CAMPAIGNS) + i]["value"]["reads"]
                       == [{k: x[k] for k in ("agent", "design", "fresh", "cached")}
                           for x in sims[s][a][w][i]["reads"]] for i in range(CAMPAIGNS)))
    ck("memory total", total == 2 * CAMPAIGNS * len(MEMORY_ARMS) * len(sal))
    ck("no engine source", not any(x.name.endswith(".py") and x.name != "verify_evd_offline.py"
                                   for x in d.rglob("*") if x.is_file()))

    print(f"{len(checks) - len(fails)}/{len(checks)} checks passed")
    for n in fails[:20]:
        print("FAIL", n)
    return 0 if not fails else 1


if __name__ == "__main__":
    raise SystemExit(main())
