#!/usr/bin/env python3
"""GBD standalone auditor — re-derives the global run registry from the revealed salts.

Rebuilds the candidate rates, the honest runs, every attacker claim set under six boundary modes,
every vote, availability, capture and cost, the registry drill, every aggregate, every hypothesis and
the verdict; then verifies the signed manifest, file hashes and Merkle root, the salt commitments, and
every Ed25519 signature and SHA-256 link of the exported memory.  Imports no CAIN code.

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

import bisect, hashlib, json, statistics, sys
from pathlib import Path

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

CANDIDATES = 12
TRIALS = 40
H_ROOTS = 10
HONEST_RUNS = 4
TRUTH = 0
DECOY = 3
P_TRUTH = 0.62
P_DECOY = 0.45
P_OTHER_LO = 0.30
P_OTHER_HI = 0.46
LUCKY_DRAWS = 2048
WORLDS = 40
CAP = 384
ROOTS = 32
MODES = ("NO_REGISTRY", "GLOBAL", "FAIL_OPEN", "FAIL_CLOSED", "PART_OPEN", "PART_MERGE")
HONEST_RUNS_TOTAL = H_ROOTS * HONEST_RUNS
TENANT, SEED = "cain42-gbd", "gbd"


def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def unit(salt, key):
    h = hashlib.sha256(f"{salt}|{key}".encode()).digest()
    return int.from_bytes(h[:8], "big") / 2 ** 64


def p_of(salt):
    p = {c: P_OTHER_LO + (P_OTHER_HI - P_OTHER_LO) * unit(salt, f"p|{c}") for c in range(CANDIDATES)}
    p[TRUTH] = P_TRUTH; p[DECOY] = P_DECOY
    return p


def cdf(n, p):
    out, cum, pmf = [], 0.0, (1.0 - p) ** n
    for k in range(n + 1):
        cum += pmf; out.append(cum)
        if k < n: pmf = pmf * (n - k) / (k + 1) * p / (1.0 - p)
    out[-1] = 1.0
    return out


def draw(u, table): return bisect.bisect_left(table, u)


def tables(salt):
    p = p_of(salt)
    return {c: cdf(TRIALS, p[c]) for c in range(CANDIDATES)}


def honest_sample(salt, world, root, cand, k, tab):
    return draw(unit(salt, f"h|{world}|{root}|{cand}|{k}"), tab[cand])


def lucky_sample(salt, world, root, tab):
    best, best_k = -1, 0
    for k in range(LUCKY_DRAWS):
        s = draw(unit(salt, f"lky|{world}|{root}|{k}"), tab[DECOY])
        if s > best: best, best_k = s, k
    return best, best_k


def luckies(salt, world, tab):
    return [lucky_sample(salt, world, j, tab)[0] for j in range(HONEST_RUNS)]


def honest_claims(salt, world, tab):
    out = []
    for r in range(H_ROOTS):
        for c in range(CANDIDATES):
            for k in range(HONEST_RUNS):
                out.append({"agent": f"H{r}-{c}-{k}", "root": f"root{r}", "candidate": c, "trials": TRIALS,
                            "successes": honest_sample(salt, world, r, c, k, tab),
                            "experiment": f"h|{world}|{r}|{c}|{k}", "sybil": False})
    return out


def attacker_claims(world, roots, luck, offset=0):
    return [{"agent": f"S{offset + r}-{j}", "root": f"syb{offset + r}", "candidate": DECOY, "trials": TRIALS,
             "successes": luck[j], "experiment": f"run|{world}|{j}", "sybil": True}
            for r in range(roots) for j in range(HONEST_RUNS)]


def materialise(salt, world, mode, tab, luck):
    honest = honest_claims(salt, world, tab)
    if mode == "FAIL_CLOSED": return [], 0.0
    if mode == "NO_REGISTRY": return honest + attacker_claims(world, ROOTS, luck), 1.0
    if mode == "GLOBAL":
        seen, kept = set(), []
        for x in attacker_claims(world, ROOTS, luck):
            if x["experiment"] not in seen: seen.add(x["experiment"]); kept.append(x)
        return honest + kept, 1.0
    if mode == "FAIL_OPEN": return honest + attacker_claims(world, ROOTS, luck), 1.0
    if mode == "PART_OPEN":
        return honest + attacker_claims(world, ROOTS, luck, 0) + attacker_claims(world, ROOTS, luck, ROOTS), 1.0
    if mode == "PART_MERGE":
        seen, kept = set(), []
        for x in attacker_claims(world, ROOTS, luck, 0) + attacker_claims(world, ROOTS, luck, ROOTS):
            if x["experiment"] not in seen: seen.add(x["experiment"]); kept.append(x)
        return honest + kept, 1.0
    raise ValueError(mode)


def score(claims, cap):
    per = {}
    for x in claims:
        a = per.setdefault((x["candidate"], x["root"]), {"s": 0, "t": 0, "exp": set()})
        a["s"] += x["successes"]; a["t"] += x["trials"]; a["exp"].add(x["experiment"])
    acc = {c: [0.0, 0.0] for c in range(CANDIDATES)}
    for (c, root), a in per.items():
        if not a["t"]: continue
        w = float(min(len(a["exp"]), cap))
        acc[c][0] += w * (a["s"] / a["t"]); acc[c][1] += w
    return {c: (v / w if w else -1.0) for c, (v, w) in acc.items()}


def select(scores): return max(range(CANDIDATES), key=lambda c: (scores[c], -c))
def evaluate(claims, cap): return select(score(claims, cap))


def votes(claims, cap):
    per = {}
    for x in claims:
        if x["candidate"] != DECOY: continue
        per.setdefault(x["root"], set()).add(x["experiment"])
    return {r: min(len(e), cap) for r, e in per.items()}


def simulate(salt, mode):
    tab = tables(salt)
    luck = {w: luckies(salt, w, tab) for w in range(WORLDS)}
    cap_yes = honest_truth = avail = 0
    vs, rs, cs, rows = [], [], [], []
    for w in range(WORLDS):
        cl, a = materialise(salt, w, mode, tab, luck[w])
        dec = evaluate(cl, CAP) if cl else None
        cap_yes += int(dec == DECOY)
        honest_truth += int(evaluate([x for x in cl if not x["sybil"]], CAP) == TRUTH) if cl else 0
        avail += int(a)
        v = sum(val for r, val in votes(cl, CAP).items() if r.startswith("syb")) if cl else 0
        runs = HONEST_RUNS
        vs.append(v); rs.append(runs); cs.append(runs / HONEST_RUNS_TOTAL)
        rows.append({"world": w, "votes": v, "capture": (dec == DECOY), "availability": a,
                     "truth_without_attacker": (evaluate([x for x in cl if not x["sybil"]], CAP) == TRUTH) if cl else False})
    return ({"capture_rate": cap_yes / WORLDS, "honest_truth_rate": honest_truth / WORLDS,
             "availability": avail / WORLDS, "attacker_votes": statistics.mean(vs),
             "attacker_runs": statistics.mean(rs), "cost_ratio": statistics.mean(cs)}, rows)


def hypotheses(m):
    H = {}
    def both(fn): return all(fn(s) for s in m)
    H["H1_global_dedup_closes_rehoming"] = {"verdict": "SUPPORTED" if both(lambda s:
        m[s]["NO_REGISTRY"]["attacker_votes"] >= 128 and m[s]["NO_REGISTRY"]["capture_rate"] >= 0.80
        and m[s]["GLOBAL"]["attacker_votes"] <= 4 and m[s]["GLOBAL"]["capture_rate"] == 0.0) else "NOT_SUPPORTED"}
    H["H2_availability_is_the_price"] = {"verdict": "SUPPORTED" if both(lambda s:
        m[s]["FAIL_OPEN"]["capture_rate"] >= 0.80 and m[s]["FAIL_CLOSED"]["availability"] == 0.0
        and m[s]["GLOBAL"]["availability"] == 1.0) else "NOT_SUPPORTED"}
    H["H3_a_partition_that_never_merges_is_two_worlds"] = {"verdict": "SUPPORTED" if both(lambda s:
        m[s]["PART_OPEN"]["attacker_votes"] >= 256 and m[s]["PART_OPEN"]["capture_rate"] >= 0.80
        and m[s]["PART_MERGE"]["attacker_votes"] <= 4 and m[s]["PART_MERGE"]["capture_rate"] == 0.0) else "NOT_SUPPORTED"}
    H["H4_honest_control_and_registry_cost"] = {"verdict": "SUPPORTED" if both(lambda s:
        all(m[s][mo]["honest_truth_rate"] == 1.0 for mo in ("NO_REGISTRY", "GLOBAL", "FAIL_OPEN", "PART_OPEN", "PART_MERGE"))
        and m[s]["FAIL_CLOSED"]["honest_truth_rate"] == 0.0) else "NOT_SUPPORTED"}
    H["H5_integrity_and_no_authority"] = {"verdict": "SUPPORTED" if both(lambda s: all(
        m[s][mo]["probe"]["chain_and_signatures"] and m[s][mo]["probe"]["replay_refused"]
        and m[s][mo]["probe"]["tamper_detected"] and m[s][mo]["probe"]["authority_from_memory_refused"]
        and m[s][mo]["probe"]["authority_flag_false_everywhere"] for mo in MODES)) else "NOT_SUPPORTED"}
    H["H6_limit_consistency_is_the_assumption"] = {"verdict": "LIMIT_CONFIRMED" if both(lambda s:
        m[s]["PART_OPEN"]["capture_rate"] > 0.0 and m[s]["PART_MERGE"]["capture_rate"] == 0.0) else "NOT_CONFIRMED"}
    H["H7_external_review"] = {"verdict": "BLOCKED"}
    core = ("H1_global_dedup_closes_rehoming", "H2_availability_is_the_price",
            "H3_a_partition_that_never_merges_is_two_worlds", "H4_honest_control_and_registry_cost",
            "H5_integrity_and_no_authority", "H6_limit_consistency_is_the_assumption")
    return H, ("GLOBAL_RUN_REGISTRY_SUPPORTED" if all(H[k]["verdict"] in ("SUPPORTED", "LIMIT_CONFIRMED") for k in core) else "NOT_SUPPORTED")


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]


def verify_entries(entries):
    prev, bad = "", 0
    for e in entries:
        body = canon({k: e[k] for k in ("seq", "tenant", "agent", "root", "kind", "key", "value", "prev",
                                        "nonce", "created_at", "grants_authority", "executable")})
        ok = (e["prev"] == prev and e["tenant"] == TENANT
              and sha(e["prev"].encode() + body + 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"]), body)
            except Exception: ok = False
        bad += 0 if ok else 1
        prev = e["hash"]
    return bad


def jn(x): return json.loads(json.dumps(x, sort_keys=True))


def main():
    d = Path(sys.argv[1])
    rep = json.loads((d / "GBD_RUN_REPORT.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    pre = json.loads((d / "GBD_PREREGISTRATION.json").read_text())
    mem = json.loads((d / "GBD_MEMORY.json").read_text())
    rows_file = json.loads((d / "GBD_ROWS.json").read_text())
    man = json.loads((d / "MANIFEST.json").read_text())
    checks, fails = [], []
    def ck(n, ok): checks.append(n); (None if ok else fails.append(n))
    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)
    EX = {"MANIFEST.json", "GBD_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "GBD_OMEGA_SEAL.json",
          "GBD_PUBKEY.pem", "GBD_SIGNED_BODY.json", "GBD_VERIFICATION_RESULTS.json", "GBD_TAMPER_RESULTS.json",
          "GBD_PUBLIC_CHECK.json"}
    fs = sorted(p for p in d.rglob("*") if p.is_file() and p.name not in EX 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")
    ck("salt commitment", {k: sha(v.encode()) for k, v in sal.items()} == pre["salts_commitment"])
    ck("status line", rep["status"] == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("modes", tuple(rep["design"]["modes"]) == MODES)

    total = 0
    for salt in mem:
        for mo in MODES:
            ck(f"memory chain {salt}:{mo}", verify_entries(mem[salt][mo]) == 0)
            ck(f"memory seq {salt}:{mo}", [e["seq"] for e in mem[salt][mo]] == list(range(1, len(mem[salt][mo]) + 1)))
            ck(f"entry count {salt}:{mo}", len(mem[salt][mo]) == rep["memory_entries"][salt][mo])
            total += len(mem[salt][mo])
    ck("memory entries total", total == sum(rep["memory_entries"][s][mo] for s in mem for mo in MODES))

    for s in sal:
        for mo in MODES:
            out, rws = simulate(sal[s], mo)
            rm = rep["measurements"][s][mo]
            ck(f"agg {s}:{mo}", jn({k: rm[k] for k in out}) == jn(out))
            ck(f"rows {s}:{mo}", jn(rows_file[s][mo]) == jn(rws))

    H, verdict = hypotheses(rep["measurements"])
    for k, v in H.items(): ck(f"hypothesis {k}", rep["hypotheses"][k]["verdict"] == v["verdict"])
    ck("verdict", rep["verdict"] == verdict)
    ck("drill", rep["registry_drill"]["distinct_first"] == 4 and rep["registry_drill"]["admitted"] == 128)
    ck("no engine source", not any(x.suffix == ".py" and x.name != "verify_gbd_offline.py" for x in d.rglob("*") if x.is_file()))

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


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