#!/usr/bin/env python3
"""EVS standalone auditor — re-derives selection, every block and every decision from the salts."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

CANDS, NULLS, ROWS, PILOT, BLOCKS, BLOCK, TOP, BAR = 60, 30, 256, 12, 5, 40, 10, 0.60
P_NULL, P_REAL_LO, P_REAL_HI = 0.50, 0.62, 0.70
ARMS = ("SAME_ADAPT", "SPLIT_ADAPT", "SAME_FIXED", "SPLIT_COMMIT", "ORACLE")
TENANT, SEED = "cain42-evs", "evs"


def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def h(s): return hashlib.sha256(s.encode()).hexdigest()
def unit(salt, *p): return int(h("|".join((salt, *map(str, p))))[:8], 16) / float(1 << 32)
def truth_p(salt, c): return P_NULL if c < NULLS else round(P_REAL_LO + (P_REAL_HI - P_REAL_LO) * unit(salt, "p", c), 6)
def order(salt, c): return sorted(range(ROWS), key=lambda i: h(f"{salt}|{c}|{i}"))
def hit(salt, c, i, p): return unit(salt, "row", c, i) < p
def pilot(salt, c):
    p = truth_p(salt, c); rows = order(salt, c)[:PILOT]
    return round(sum(1 for i in rows if hit(salt, c, i, p)) / PILOT, 6)
def block_score(salt, c, b):
    p = truth_p(salt, c); rows = order(salt, c)[PILOT + b * BLOCK: PILOT + (b + 1) * BLOCK]
    return round(sum(1 for i in rows if hit(salt, c, i, p)) / len(rows), 6)
def commitment(salt, b): return h(f"{salt}|commit|{b}")
def select(salt): return sorted(range(CANDS), key=lambda c: (-pilot(salt, c), c))[:TOP]


def decisions(salt, arm):
    out = []
    for c in select(salt):
        p = truth_p(salt, c); sc = [block_score(salt, c, b) for b in range(BLOCKS)]
        if arm in ("SAME_ADAPT", "SPLIT_ADAPT"):
            rep = max(sc); b = sc.index(rep)
        elif arm in ("SAME_FIXED", "SPLIT_COMMIT"):
            b = 0; rep = sc[0]
        else:
            b = -1; rep = p
        out.append({"candidate": c, "truth_p": p, "real": p >= BAR, "pilot": pilot(salt, c), "block": b,
                    "reported": round(rep, 6), "overclaim": round(rep - p, 6), "promote": rep >= BAR,
                    "commitment": (commitment(salt, 0) if arm in ("SAME_FIXED", "SPLIT_COMMIT") else None)})
    return out


def stats(rows):
    pr = [r for r in rows if r["promote"]]
    return {"promotions": len(pr),
            "overclaim": round(sum(r["overclaim"] for r in pr) / len(pr), 6) if pr else 0.0,
            "false_promotions": sum(1 for r in pr if not r["real"]),
            "true_promotions": sum(1 for r in pr if r["real"]), "selected": len(rows),
            "selected_real": sum(1 for r in rows if r["real"]),
            "reported_mean": round(sum(r["reported"] for r in rows) / len(rows), 6),
            "true_mean": round(sum(r["truth_p"] for r in rows) / len(rows), 6)}


def nonce(a, k, key, v): return sha(canon({"agent": a, "kind": k, "key": key, "value": v}))[:16]
def pub_of(a):
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


def verify_memory(es, pubs):
    prev, bad = "", []
    for e in es:
        e = {**e, "grants_authority": False, "executable": False}
        body = 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
        ok = ok and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"]
        ok = ok and e["nonce"] == nonce(e["agent"], e["kind"], e["key"], e["value"])
        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"")


def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve(); ck, fail = [], []
    def check(n, ok, d=""):
        ck.append({"check": n, "ok": bool(ok), "detail": d})
        if not ok: fail.append(n)
    args = json.loads((root / "EVS_RUN_REPORT.json").read_text()); rows = json.loads((root / "EVS_ROWS.json").read_text())
    mem = json.loads((root / "EVS_MEMORY.json").read_text()); salts = json.loads((root / "SALTS.json").read_text())
    pre = json.loads((root / "EVS_PREREGISTRATION.json").read_text()); man = json.loads((root / "MANIFEST.json").read_text())
    for k in ("salt1", "salt2"): check(f"salt commitment {k}", sha(salts[k].encode()) == pre["salts_commitment"][k])
    derived = {s: {a: decisions(salts[s], a) for a in ARMS} for s in ("salt1", "salt2")}
    index = {(r["salt"], r["arm"], r["candidate"]): r for r in rows}
    mism = 0
    for s in derived:
        for a in ARMS:
            for d in derived[s][a]:
                r = index.get((s, a, d["candidate"]))
                if r is None or any(r[k] != d[k] for k in ("truth_p", "real", "pilot", "block", "reported", "overclaim", "promote", "commitment")):
                    mism += 1
    check("every candidate, block and decision re-derives", mism == 0, f"{mism} mismatches")
    mm = 0
    for s in derived:
        for a in ARMS:
            exp = stats(derived[s][a]); rep = args["measurements"][s][a]
            if any(rep.get(k) != v for k, v in exp.items()): mm += 1
    check("measurement summary re-derives", mm == 0, f"{mm} mismatches")
    h1 = all(stats(derived[s]["SAME_ADAPT"])["overclaim"] >= 0.04 for s in derived)
    h2 = all(all(derived[s]["SAME_ADAPT"][i]["reported"] == derived[s]["SPLIT_ADAPT"][i]["reported"]
                 and derived[s]["SAME_ADAPT"][i]["promote"] == derived[s]["SPLIT_ADAPT"][i]["promote"] for i in range(TOP)) for s in derived)
    h3 = True
    for s in derived:
        a, c = stats(derived[s]["SAME_ADAPT"]), stats(derived[s]["SPLIT_COMMIT"])
        h3 = h3 and (a["overclaim"] - c["overclaim"]) >= 0.03 and c["false_promotions"] <= a["false_promotions"]
    h4 = all(all(derived[s]["SAME_FIXED"][i]["reported"] == derived[s]["SPLIT_COMMIT"][i]["reported"]
                 and derived[s]["SAME_FIXED"][i]["promote"] == derived[s]["SPLIT_COMMIT"][i]["promote"] for i in range(TOP)) for s in derived)
    computed = {"H1_adaptive_evaluation_overclaims": "SUPPORTED" if h1 else "NOT_SUPPORTED",
                "H2_role_separation_changes_nothing_alone": "SUPPORTED" if h2 else "NOT_SUPPORTED",
                "H3_precommitment_removes_the_inflation": "SUPPORTED" if h3 else "NOT_SUPPORTED",
                "H4_protocol_not_identity": "SUPPORTED" if h4 else "NOT_SUPPORTED"}
    check("H1-H4 recomputed (a NOT_SUPPORTED hypothesis is a valid result)", True, json.dumps(computed))
    pubs = {a: pub_of(a) for a in ("selector", "evaluator", "auditor")}
    check("published memory keys derive from the seed", pubs == mem["keys"])
    bad = []
    for key, es in mem["entries"].items(): bad += [(key, b) for b in verify_memory(es, pubs)]
    check("every governed-memory entry verifies", not bad, str(bad[:5]))
    ok_probe = all(args["probes"][s]["chain_and_signatures"] and args["probes"][s]["replay_refused"]
                   and args["probes"][s]["tamper_detected"] and args["probes"][s]["commitment_before_pilot"]
                   and args["probes"][s]["authority_from_memory_refused"] and args["probes"][s]["authority_flag_false_everywhere"]
                   for s in ("salt1", "salt2"))
    for s in ("salt1", "salt2"):
        cs = [e["seq"] for e in mem["entries"][s] if e["kind"] == "commitment"]
        ps = [e["seq"] for e in mem["entries"][s] if e["kind"] == "pilot"]
        check(f"{s} every commitment precedes every pilot", bool(cs) and bool(ps) and max(cs) < min(ps))
    check("H5 integrity, ordering and no authority", ok_probe)
    check("reported hypothesis verdicts match", {k: v.get("verdict") for k, v in args["hypotheses"].items()}
          == {**computed, "H5_integrity_and_commitment_ordering": "SUPPORTED" if ok_probe else "NOT_SUPPORTED",
              "H6_external_review": "BLOCKED"})
    check("verdict follows", args["verdict"] == ("PRE_COMMITTED_EVALUATION_SUPPORTED" if all([h1, h2, h3, h4, ok_probe]) else "NOT_SUPPORTED"))
    fs = sorted(p for p in root.rglob("*") if p.is_file() and "__pycache__" not in p.parts
                and p.name not in ("MANIFEST.json", "EVS_MANIFEST.json", "MERKLE_ROOT.txt", "EVS_SIGNED_BODY.json",
                                   "EVS_VERIFICATION_RESULTS.json", "EVS_TAMPER_RESULTS.json", "EVS_PUBLIC_CHECK.json",
                                   "PUBLICATION.json", "EVS_OMEGA_SEAL.json", "EVS_PUBKEY.pem"))
    body = {k: man[k] for k in ("schema", "evolution", "status", "name", "created_at", "verifier", "pubkey_ed25519", "files", "merkle_root", "engine_withheld", "external_review")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body)); check("manifest signature", True)
    except Exception: check("manifest signature", False)
    check("file hashes match", all(man["files"].get(str(p.relative_to(root))) == sha(p.read_bytes()) for p in fs))
    check("manifest lists exactly the bundle files", sorted(man["files"]) == sorted(str(p.relative_to(root)) for p in fs))
    check("merkle root recomputes", man["merkle_root"] == merkle(fs))
    check("engine source withheld", man.get("engine_withheld") is True and not any(p.suffix == ".py" and "verify" not in p.name for p in fs))
    check("no model calls", args.get("model_calls") == 0)
    check("status line", args.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    check("external review not claimed", man.get("external_review") == "NOT_OBTAINED")
    print(json.dumps({"checks": len(ck), "passed": sum(1 for c in ck if c["ok"]), "failed": fail, "verdict": args["verdict"]}, indent=1))
    return 0 if not fail else 1


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