#!/usr/bin/env python3
"""DST standalone auditor — re-derives distinctness and completeness from the revealed salts.

Rebuilds the candidate rates, the ten honest roots and their four distinct runs, every bought root
under all four regimes and two caps, every vote count, every attacker run count and cost ratio, 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
governed memory.  Imports no CAIN code.

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

import bisect
import hashlib
import json
import math
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 = 10
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
HONEST_RUNS = 4
CAPS = (4, 384)
REGIMES = ("OPEN", "DEDUP", "SELECT", "FULL")
BAR = math.ceil(TRIALS * P_TRUTH)
HONEST_RUNS_TOTAL = H_ROOTS * HONEST_RUNS
TENANT, SEED = "cain42-dst", "dst"


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 pmf(n, p):
    out, q = [], (1.0 - p) ** n
    for k in range(n + 1):
        out.append(q)
        if k < n:
            q = q * (n - k) / (k + 1) * p / (1.0 - p)
    return out


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 tail(bar):
    w = pmf(TRIALS, P_DECOY)
    hit = sum(w[bar:])
    mean = sum(k * w[k] for k in range(bar, TRIALS + 1)) / hit if hit else 0.0
    return hit, mean


def runs_for(votes, bar):
    hit, _ = tail(bar)
    return max(1, math.ceil(votes / hit)) if hit else 10 ** 9


def claims_for(salt, world, regime, cap, 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})
    if regime == "OPEN":
        lucky, _ = lucky_sample(salt, world, 0, tab)
        for j in range(cap):
            out.append({"agent": f"S-{j}", "root": "syb0", "candidate": DECOY, "trials": TRIALS,
                        "successes": lucky, "experiment": f"declared|{world}|0|{j}", "sybil": True})
    elif regime == "DEDUP":
        lucky, best_k = lucky_sample(salt, world, 0, tab)
        for j in range(cap):
            out.append({"agent": f"S-{j}", "root": "syb0", "candidate": DECOY, "trials": TRIALS,
                        "successes": lucky, "experiment": f"run|{world}|0|{best_k}", "sybil": True})
    else:
        bar = max(1, math.ceil(TRIALS * float(p_of(salt)[TRUTH])))
        hit, cond = tail(bar)
        if regime == "SELECT":
            sel = int(round(cond))
            for j in range(cap):
                out.append({"agent": f"S-{j}", "root": "syb0", "candidate": DECOY, "trials": TRIALS,
                            "successes": sel, "experiment": f"run|{world}|0|sel{j}", "sybil": True})
        else:
            for j in range(cap):
                out.append({"agent": f"S-{j}", "root": "syb0", "candidate": DECOY, "trials": TRIALS,
                            "successes": draw(unit(salt, f"full|{world}|0|{j}"), tab[DECOY]),
                            "experiment": f"run|{world}|0|full{j}", "sybil": True})
    return out


def attacker_cost(regime, cap, bar):
    if regime in ("OPEN", "DEDUP"):
        return 1
    if regime == "SELECT":
        return runs_for(cap, bar)
    return cap


# ---------------------------------------------------------------- policy (mirrored)

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, regime, cap):
    tab = tables(salt)
    per_world = [claims_for(salt, w, regime, cap, tab) for w in range(WORLDS)]
    captures, honest_truth, vs, rs, cs, rows = 0, 0, [], [], [], []
    for cl in per_world:
        honest = [x for x in cl if not x["sybil"]]
        dec = evaluate(cl, cap)
        captures += int(dec == DECOY)
        honest_truth += int(evaluate(honest, cap) == TRUTH)
        v = votes(cl, cap).get("syb0", 0)
        vs.append(v)
        r = attacker_cost(regime, cap, BAR)
        rs.append(r); cs.append(r / HONEST_RUNS_TOTAL)
        rows.append({"world": len(rows), "votes": v, "capture": dec == DECOY,
                     "truth_without_attacker": evaluate(honest, cap) == TRUTH})
    hit, cond = tail(BAR)
    out = {"capture_rate": captures / WORLDS, "honest_truth_rate": honest_truth / WORLDS,
           "attacker_votes": statistics.mean(vs), "attacker_runs": statistics.mean(rs),
           "cost_ratio": statistics.mean(cs), "bar": BAR, "p_hit": hit, "cond_mean": cond / TRIALS}
    return out, rows


def hypotheses(m):
    H = {}

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

    H["H1_duplication_needs_distinctness"] = {
        "verdict": "SUPPORTED" if both(lambda s: m[s]["OPEN_c384"]["capture_rate"] >= 0.80
                                       and m[s]["DEDUP_c384"]["capture_rate"] == 0.0) else "NOT_SUPPORTED"}
    H["H2_selection_survives_a_receipt_at_a_price"] = {
        "verdict": "SUPPORTED" if both(lambda s: m[s]["SELECT_c384"]["capture_rate"] >= 0.50
                                       and m[s]["SELECT_c384"]["cost_ratio"] >= 100
                                       and m[s]["FULL_c384"]["capture_rate"] == 0.0) else "NOT_SUPPORTED"}
    H["H3_either_property_alone_leaves_an_attack"] = {
        "verdict": "SUPPORTED" if both(lambda s: m[s]["SELECT_c384"]["capture_rate"] > 0.0
                                       and m[s]["OPEN_c384"]["capture_rate"] > 0.0
                                       and m[s]["DEDUP_c384"]["capture_rate"] == 0.0
                                       and m[s]["FULL_c384"]["capture_rate"] == 0.0) else "NOT_SUPPORTED"}
    H["H4_honest_control"] = {
        "verdict": "SUPPORTED" if both(lambda s: all(m[s][f"{r}_c{c}"]["honest_truth_rate"] == 1.0
                                                     for r in REGIMES for c in CAPS)) else "NOT_SUPPORTED"}
    H["H5_integrity_and_no_authority"] = {
        "verdict": "SUPPORTED" if both(lambda s: all(m[s][f"{r}_c{c}"]["probe"]["chain_and_signatures"]
                                                     and m[s][f"{r}_c{c}"]["probe"]["replay_refused"]
                                                     and m[s][f"{r}_c{c}"]["probe"]["tamper_detected"]
                                                     and m[s][f"{r}_c{c}"]["probe"]["authority_from_memory_refused"]
                                                     and m[s][f"{r}_c{c}"]["probe"]["authority_flag_false_everywhere"]
                                                     for r in REGIMES for c in CAPS)) else "NOT_SUPPORTED"}
    H["H6_limit_a_small_cap_is_the_cheapest_defence"] = {
        "verdict": "LIMIT_CONFIRMED" if both(lambda s: all(m[s][f"{r}_c4"]["capture_rate"] == 0.0 for r in REGIMES)) else "NOT_CONFIRMED"}
    H["H7_external_review"] = {"verdict": "BLOCKED"}
    core = ("H1_duplication_needs_distinctness", "H2_selection_survives_a_receipt_at_a_price",
            "H3_either_property_alone_leaves_an_attack", "H4_honest_control",
            "H5_integrity_and_no_authority", "H6_limit_a_small_cap_is_the_cheapest_defence")
    ok = all(H[k]["verdict"] in ("SUPPORTED", "LIMIT_CONFIRMED") for k in core)
    return H, ("DISTINCT_COMPLETE_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 / "DST_RUN_REPORT.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    pre = json.loads((d / "DST_PREREGISTRATION.json").read_text())
    mem = json.loads((d / "DST_MEMORY.json").read_text())
    rows_file = json.loads((d / "DST_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", "DST_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "DST_OMEGA_SEAL.json",
          "DST_PUBKEY.pem", "DST_SIGNED_BODY.json", "DST_VERIFICATION_RESULTS.json",
          "DST_TAMPER_RESULTS.json", "DST_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("regimes", tuple(rep["design"]["regimes"]) == REGIMES)
    ck("caps", tuple(rep["design"]["caps"]) == CAPS)

    total = 0
    for salt in mem:
        for r in REGIMES:
            for c in CAPS:
                key = f"{r}_c{c}"
                entries = mem[salt][key]
                ck(f"memory chain {salt}:{key}", verify_entries(entries) == 0)
                ck(f"memory seq {salt}:{key}", [e["seq"] for e in entries] == list(range(1, len(entries) + 1)))
                ck(f"entry count {salt}:{key}", len(entries) == rep["memory_entries"][salt][key])
                total += len(entries)
    ck("memory entries total", total == sum(rep["memory_entries"][s][k] for s in mem for k in rep["memory_entries"][s]))

    for s in sal:
        for c in CAPS:
            for r in REGIMES:
                key = f"{r}_c{c}"
                out, rws = simulate(sal[s], r, c)
                rm = rep["measurements"][s][key]
                ck(f"agg {s}:{key}", jn({k: rm[k] for k in out}) == jn(out))
                ck(f"rows {s}:{key}", jn(rows_file[s][key]) == 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("no engine source", not any(x.suffix == ".py" and x.name != "verify_dst_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())
