#!/usr/bin/env python3
"""SIB standalone auditor — re-derives the entire provenance-vote study from the revealed salts.

Rebuilds the declared success rates, every honest shard and every selectively reported Sybil run;
replays all eight conditions and all five promotion policies; recomputes every selection, every key
and root flip threshold, every aggregate, every hypothesis and the verdict; 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.  Imports no CAIN code.

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

import bisect
import hashlib
import json
import statistics
import 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 = 4
IDS_PER_ROOT = 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
FAKE_CLAIM = 38
WORLDS = 40
TENANT, SEED = "cain42-sib", "sib"
CONDITIONS = {
    "HONEST": {"h": 4, "roots": 0, "ids": 0, "mode": "none"},
    "INDEP": {"h": 4, "roots": 0, "ids": 0, "mode": "independent_replicate"},
    "FAB": {"h": 4, "roots": 1, "ids": 24, "mode": "fabricate"},
    "DUP": {"h": 4, "roots": 1, "ids": 24, "mode": "duplicate"},
    "DUP256": {"h": 4, "roots": 1, "ids": 256, "mode": "duplicate"},
    "MIX": {"h": 4, "roots": 1, "ids": 24, "mode": "mix"},
    "ROOTS12": {"h": 4, "roots": 12, "ids": 8, "mode": "duplicate"},
    "HARDENED": {"h": 10, "roots": 1, "ids": 256, "mode": "duplicate"},
}
CONDITION_ORDER = ("HONEST", "INDEP", "FAB", "DUP", "DUP256", "MIX", "ROOTS12", "HARDENED")
POLICIES = ("KEY", "VERIFIED", "ROOT", "ROOT_Q2", "ORACLE")


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 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_agents(h):
    return [(f"H{r}{k}", f"root{r}", [c for c in range(CANDIDATES) if c % IDS_PER_ROOT == k])
            for r in range(h) for k in range(IDS_PER_ROOT)]


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


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


def fake_true(salt, world, agent, tab):
    return draw(unit(salt, f"fab|{world}|{agent}"), tab[DECOY])


def true_result(salt, claim, tab):
    parts = claim["experiment"].split("|")
    kind, world = parts[0], int(parts[1])
    if kind == "h":
        return honest_sample(salt, world, int(parts[2]), int(parts[3]), tab)
    if kind == "lucky":
        return draw(unit(salt, f"lky|{world}|{parts[2]}|{parts[3]}"), tab[DECOY])
    if kind == "fab":
        return fake_true(salt, world, claim["agent"], tab)
    raise ValueError(claim["experiment"])


def claims_for(salt, world, condition, tab=None, lucky_cache=None):
    tab = tab or tables(salt)
    spec = CONDITIONS[condition]
    h = spec["h"]
    out = []
    for aid, root, cands in honest_agents(h):
        for c in cands:
            out.append({"agent": aid, "root": root, "candidate": c, "trials": TRIALS,
                        "successes": honest_sample(salt, world, int(root[4:]), c, tab),
                        "experiment": f"h|{world}|{root[4:]}|{c}", "sybil": False})
    if condition == "INDEP":
        for aid, root, cands in honest_agents(h):
            if root != "root0":
                continue
            for c in cands:
                out.append({"agent": f"I{aid}", "root": "root4", "candidate": c, "trials": TRIALS,
                            "successes": honest_sample(salt, world, 4, c, tab),
                            "experiment": f"h|{world}|4|{c}", "sybil": False})
    for ri in range(spec["roots"]):
        key = (salt, world, ri)
        if lucky_cache is not None and key in lucky_cache:
            lucky, best_k = lucky_cache[key]
        else:
            lucky, best_k = lucky_sample(salt, world, ri, tab)
            if lucky_cache is not None:
                lucky_cache[key] = (lucky, best_k)
        for k in range(spec["ids"]):
            agent = f"S{ri:02d}-{k:03d}"
            fake = spec["mode"] == "fabricate" or (spec["mode"] == "mix" and k < spec["ids"] // 2)
            if fake:
                out.append({"agent": agent, "root": f"syb{ri}", "candidate": DECOY, "trials": TRIALS,
                            "successes": FAKE_CLAIM, "experiment": f"fab|{world}|{agent}", "sybil": True})
            else:
                out.append({"agent": agent, "root": f"syb{ri}", "candidate": DECOY, "trials": TRIALS,
                            "successes": lucky, "experiment": f"lucky|{world}|{ri}|{best_k}",
                            "sybil": True})
    return out


# ---------------------------------------------------------------- policies (mirrored)

def _pool(claims):
    acc = {c: [0, 0] for c in range(CANDIDATES)}
    for x in claims:
        a = acc[x["candidate"]]
        a[0] += x["successes"]
        a[1] += x["trials"]
    return {c: (s / t if t else -1.0) for c, (s, t) in acc.items()}


def _root_scores(claims):
    per = {}
    for x in claims:
        k = (x["candidate"], x["root"])
        a = per.setdefault(k, [0, 0])
        a[0] += x["successes"]
        a[1] += x["trials"]
    votes = {c: [] for c in range(CANDIDATES)}
    for (c, root), (s, t) in per.items():
        if t:
            votes[c].append(s / t)
    return {c: (sum(v) / len(v) if v else -1.0, len(v)) for c, v in votes.items()}


def _root_means(claims):
    per = {}
    for x in claims:
        a = per.setdefault((x["candidate"], x["root"]), [0, 0])
        a[0] += x["successes"]
        a[1] += x["trials"]
    return {k: (v[0] / v[1] if v[1] else 0.0, 1) for k, v in per.items()}


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


def evaluate(salt, claims, policy, tab):
    if policy == "ORACLE":
        p = p_of(salt)
        return max(range(CANDIDATES), key=lambda c: (p[c], -c))
    if policy == "VERIFIED":
        kept = [x for x in claims if x["successes"] == true_result(salt, x, tab)]
        return select(_pool(kept))
    if policy == "KEY":
        return select(_pool(claims))
    if policy == "ROOT":
        return select({c: v[0] for c, v in _root_scores(claims).items()})
    if policy == "ROOT_Q2":
        return select({c: (v[0] if v[1] >= 2 else -1.0) for c, v in _root_scores(claims).items()})
    raise ValueError(policy)


def keys_to_flip(claims, lucky):
    honest = [x for x in claims if not x["sybil"]]
    dec = [x for x in honest if x["candidate"] == DECOY]
    tru = [x for x in honest if x["candidate"] == TRUTH]
    sd, td = sum(x["successes"] for x in dec), sum(x["trials"] for x in dec)
    st, tt = sum(x["successes"] for x in tru), sum(x["trials"] for x in tru)
    if not tt:
        return 1025
    target = st / tt
    den = lucky - TRIALS * target
    if den <= 1e-12:
        return 1025
    need = target * td - sd
    s = max(1, int(need // den) + (1 if need % den else 0))
    return min(s, 1025)


def roots_to_flip(claims, lucky_mean):
    honest = [x for x in claims if not x["sybil"]]
    tru = [v[0] for (c, _), v in _root_means([x for x in honest if x["candidate"] == TRUTH]).items()]
    dec = [v[0] for (c, _), v in _root_means([x for x in honest if x["candidate"] == DECOY]).items()]
    if not tru or not dec:
        return 65
    target = sum(tru) / len(tru)
    a, n = sum(dec), len(dec)
    den = lucky_mean - target
    if den <= 1e-12:
        return 65
    need = target * n - a
    r = max(1, int(need // den) + (1 if need % den else 0))
    return min(max(r, 1), 65)


def weight_shares(claims):
    dec = [x for x in claims if x["candidate"] == DECOY]
    key_tot = sum(x["trials"] for x in dec) or 1
    key_syb = sum(x["trials"] for x in dec if x["sybil"])
    roots = {x["root"] for x in dec}
    syb_roots = {x["root"] for x in dec if x["sybil"]}
    return {"key": key_syb / key_tot, "root": (len(syb_roots) / len(roots)) if roots else 0.0,
            "decoy_roots": len(roots), "sybil_roots": len(syb_roots)}


def voice(claims):
    dec = [x for x in claims if x["candidate"] == DECOY]
    key_tot = sum(x["trials"] for x in dec) or 1
    roots = {x["root"] for x in dec}
    return {"key": TRIALS / (key_tot + TRIALS), "root": 1.0 / (len(roots) + 1)}


def campaign(salt, condition, tab=None, lucky_cache=None):
    tab = tables(salt)
    lucky_cache = {} if lucky_cache is None else lucky_cache
    p = p_of(salt)
    rows, agg = [], {pol: {"decoy": 0, "truth": 0, "other": 0, "promoted": []} for pol in POLICIES}
    kflip, rflip = [], []
    for w in range(WORLDS):
        cl = claims_for(salt, w, condition, tab, lucky_cache)
        lucky, _ = lucky_cache[(salt, w, 0)] if (salt, w, 0) in lucky_cache else lucky_sample(salt, w, 0, tab)
        kf = keys_to_flip(cl, lucky)
        rf = roots_to_flip(cl, lucky / TRIALS)
        kflip.append(kf)
        rflip.append(rf)
        per = {}
        for pol in POLICIES:
            sel = evaluate(salt, cl, pol, tab)
            decoy, truth = sel == DECOY, sel == TRUTH
            agg[pol]["decoy"] += int(decoy)
            agg[pol]["truth"] += int(truth)
            agg[pol]["other"] += int(not decoy and not truth)
            agg[pol]["promoted"].append(p[sel])
            per[pol] = {"selected": sel, "decoy": decoy, "truth": truth, "promoted_p": p[sel]}
        rows.append({"world": w, "lucky": lucky, "keys_to_flip": kf, "roots_to_flip": rf, "policies": per})
    out = {}
    for pol in POLICIES:
        a = agg[pol]
        out[pol] = {"decoy": a["decoy"], "truth": a["truth"], "other": a["other"],
                    "decoy_rate": a["decoy"] / WORLDS, "truth_rate": a["truth"] / WORLDS,
                    "other_rate": a["other"] / WORLDS,
                    "promoted_p_mean": statistics.mean(a["promoted"]),
                    "promoted_p_min": min(a["promoted"]), "promoted_p_max": max(a["promoted"])}
    extra = {"keys_to_flip_median": statistics.median(kflip), "keys_to_flip_min": min(kflip),
             "keys_to_flip_max": max(kflip), "roots_to_flip_median": statistics.median(rflip),
             "roots_to_flip_min": min(rflip), "roots_to_flip_max": max(rflip),
             "weight": weight_shares(claims_for(salt, 0, condition, tab, lucky_cache)),
             "voice": voice(claims_for(salt, 0, condition, tab, lucky_cache))}
    return out, rows, extra


def root_bounds():
    out = {}
    for H in (4, 10):
        worst = (H * P_DECOY + 1.0) / (H + 1)
        sd = ((P_TRUTH * (1 - P_TRUTH)) / (H * TRIALS)) ** 0.5
        margin = (P_TRUTH - worst) / sd
        out[str(H)] = {"worst_decoy": worst, "sigma": sd, "margin_sigma": margin,
                       "structurally_safe": margin >= 3.0}
    return out


def hypotheses(m):
    H = {}

    def both(fn):
        return all(fn(s) for s in m)

    d = m
    key_dup = {s: d[s]["DUP"]["KEY"]["decoy_rate"] for s in d}
    ver_dup = {s: d[s]["DUP"]["VERIFIED"]["decoy_rate"] for s in d}
    H["H1_verification_cannot_defeat_duplication"] = {
        "verdict": "SUPPORTED" if both(lambda s: ver_dup[s] >= key_dup[s] - 0.02 and key_dup[s] >= 0.70) else "NOT_SUPPORTED"}
    H["H2_provenance_defeats_single_principal"] = {
        "verdict": "SUPPORTED" if both(lambda s: d[s]["HARDENED"]["ROOT"]["decoy_rate"] == 0.0
                                       and d[s]["HARDENED"]["KEY"]["decoy_rate"] >= 0.70
                                       and d[s]["DUP256"]["KEY"]["decoy_rate"] >= 0.70) else "NOT_SUPPORTED"}
    H["H3_root_weighting_costs_nothing_honest"] = {
        "verdict": "SUPPORTED" if both(lambda s: all(d[s]["HONEST"][p]["truth_rate"] >= 0.90
                                                     and d[s]["HONEST"][p]["decoy_rate"] <= 0.10
                                                     for p in ("KEY", "VERIFIED", "ROOT", "ROOT_Q2"))) else "NOT_SUPPORTED"}
    H["H4_keys_scale_roots_do_not"] = {
        "verdict": "SUPPORTED" if both(lambda s: d[s]["DUP256"]["keys_to_flip_median"] <= 32
                                       and d[s]["HARDENED"]["ROOT"]["decoy_rate"] <= 0.02
                                       and d[s]["DUP256"]["roots_to_flip_median"] >= 5) else "NOT_SUPPORTED"}
    H["H5_fabrication_is_caught_by_verification"] = {
        "verdict": "SUPPORTED" if both(lambda s: d[s]["FAB"]["VERIFIED"]["decoy_rate"] <= 0.05
                                       and d[s]["FAB"]["KEY"]["decoy_rate"] >= 0.70) else "NOT_SUPPORTED"}
    H["H6_limit_is_a_root_majority"] = {
        "verdict": "LIMIT_CONFIRMED" if both(lambda s: d[s]["ROOTS12"]["ROOT"]["decoy_rate"] >= 0.50) else "NOT_CONFIRMED"}
    ok7 = both(lambda s: all(d[s][c]["probe"]["chain_and_signatures"] and d[s][c]["probe"]["replay_refused"]
                             and d[s][c]["probe"]["tamper_detected"]
                             and d[s][c]["probe"]["authority_from_memory_refused"]
                             and d[s][c]["probe"]["authority_flag_false_everywhere"]
                             for c in CONDITION_ORDER))
    H["H7_integrity_and_no_authority"] = {"verdict": "SUPPORTED" if ok7 else "NOT_SUPPORTED"}
    H["H8_external_review"] = {"verdict": "BLOCKED"}
    core = ("H1_verification_cannot_defeat_duplication", "H2_provenance_defeats_single_principal",
            "H3_root_weighting_costs_nothing_honest", "H4_keys_scale_roots_do_not",
            "H5_fabrication_is_caught_by_verification", "H6_limit_is_a_root_majority",
            "H7_integrity_and_no_authority")
    ok = all(H[k]["verdict"] in ("SUPPORTED", "LIMIT_CONFIRMED") for k in core)
    return H, ("PROVENANCE_VOTE_SUPPORTED" if ok else "NOT_SUPPORTED")


# ---------------------------------------------------------------- memory

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 / "SIB_RUN_REPORT.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    pre = json.loads((d / "SIB_PREREGISTRATION.json").read_text())
    mem = json.loads((d / "SIB_MEMORY.json").read_text())
    rows_file = json.loads((d / "SIB_ROWS.json").read_text())
    man = json.loads((d / "MANIFEST.json").read_text())
    checks, fails = [], []

    def ck(n, ok):
        checks.append(n)
        if not ok:
            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", "SIB_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
          "SIB_OMEGA_SEAL.json", "SIB_PUBKEY.pem", "SIB_SIGNED_BODY.json",
          "SIB_VERIFICATION_RESULTS.json", "SIB_TAMPER_RESULTS.json", "SIB_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("conditions", tuple(rep["design"]["conditions"]) == CONDITION_ORDER)
    ck("policies", tuple(rep["design"]["policies"]) == POLICIES)

    total = 0
    for salt in mem:
        for cond in CONDITION_ORDER:
            entries = mem[salt][cond]
            bad = verify_entries(entries)
            total += len(entries)
            ck(f"memory chain {salt}:{cond}", bad == 0)
            ck(f"memory seq {salt}:{cond}", [e["seq"] for e in entries] == list(range(1, len(entries) + 1)))
            ck(f"entry count {salt}:{cond}", len(entries) == rep["memory_entries"][salt][cond])
            ck(f"entry roots {salt}:{cond}", all(e["root"] for e in entries))
    ck("memory entries total", total == sum(rep["memory_entries"][s][c] for s in mem for c in CONDITION_ORDER))

    sims = {}
    for s in sal:
        sims[s] = {}
        for cond in CONDITION_ORDER:
            # stateless per condition, exactly like the run: recompute the tables and a fresh cache.
            sims[s][cond] = campaign(sal[s], cond)
    for s in sal:
        for cond in CONDITION_ORDER:
            agg, rws, extra = sims[s][cond]
            rm = rep["measurements"][s][cond]
            for pol in POLICIES:
                ck(f"agg {s}:{cond}:{pol}", jn({k: rm[pol][k] for k in agg[pol]}) == jn(agg[pol]))
            def slim(r):
                return {**r, "policies": {k: {q: v[q] for q in ("selected", "decoy", "truth", "promoted_p")}
                                          for k, v in r["policies"].items()}}
            ck(f"rows {s}:{cond}", jn([slim(r) for r in rows_file[s][cond]]) == jn([slim(r) for r in rws]))
            for k in ("keys_to_flip_median", "keys_to_flip_min", "keys_to_flip_max",
                      "roots_to_flip_median", "roots_to_flip_min", "roots_to_flip_max", "weight", "voice"):
                ck(f"{k} {s}:{cond}", jn(rm[k]) == jn(extra[k]))

    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("root bound", jn(rep["analysis"]["root_bound"]) == jn(root_bounds()))
    ck("drill", all(rep["drill"][s]["distinct"] == 4 and rep["drill"][s]["chain_and_signatures"]
                    for s in rep["drill"]))
    ck("no engine source", not any(x.suffix == ".py" and x.name != "verify_sib_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())
