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

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

import hashlib
import json
import sys
from pathlib import Path

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

FEATURES = 8
ROWS = 256
CANDIDATES = 40
AGENTS = 4
PER_AGENT = 10
P_N, H_N, U_N = 128, 112, 16
SEL_N = 12
CONF_POOL = 96
WORLDS = 12
ARMS = ("TOP1", "TOP2", "TOP3", "TOP4", "TOP6", "TOP8", "ORACLE")
MEMORY_ARMS = ARMS[:-1]
KS = {"TOP1": 1, "TOP2": 2, "TOP3": 3, "TOP4": 4, "TOP6": 6, "TOP8": 8}
TENANT, SEED = "cain42-cba", "cba"
AGENT_IDS = tuple(f"agent{i}" for i in range(AGENTS))
SIGNERS = AGENT_IDS + ("verifier",)
CHECKS = []


def ok(name, cond):
    CHECKS.append((name, bool(cond)))
    return bool(cond)


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


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


def bit(row, f):
    return (row >> f) & 1


def rank(salt, tag, rows):
    return sorted(rows, key=lambda r: hashlib.sha256(f"{salt}|{tag}|{r}".encode()).digest())


def truth_table(salt):
    terms = []
    for t in range(3):
        feats, vals, j = [], [], 0
        while len(feats) < 3:
            f = int(hashlib.sha256(f"{salt}|truth|{t}|{j}".encode()).hexdigest()[:2], 16) % FEATURES
            if f not in feats:
                feats.append(f)
                vals.append(int(hashlib.sha256(f"{salt}|truth|{t}|{j}|v".encode()).hexdigest()[:2], 16) & 1)
            j += 1
        terms.append((tuple(feats), tuple(vals)))
    return tuple(1 if any(all(bit(r, f) == v for f, v in zip(fs, vs)) for fs, vs in terms) else 0
                 for r in range(ROWS))


def candidate(salt, j, R):
    h = hashlib.sha256(f"{salt}|support|{j}".encode()).digest()
    fa = h[0] % FEATURES
    fb = (fa + 1 + h[1] % (FEATURES - 1)) % FEATURES
    pa, pb = h[2] & 1, h[3] & 1
    inside = set(r for r in range(ROWS) if bit(r, fa) == pa and bit(r, fb) == pb)
    h2 = hashlib.sha256(f"{salt}|cand|{j}".encode()).digest()
    d_in = 0.02 + 0.08 * (int.from_bytes(h2[4:12], "big") / 2 ** 64)
    d_out = 0.22 + 0.22 * (int.from_bytes(h2[12:20], "big") / 2 ** 64)
    table = []
    for r in range(ROWS):
        d = d_in if r in inside else d_out
        flip = (int.from_bytes(hashlib.sha256(f"{salt}|flip|{j}|{r}".encode()).digest()[:8], "big") / 2 ** 64) < d
        table.append(1 - R[r] if flip else R[r])
    table = tuple(table)
    return {"table": table, "acc": round(sum(1 for a, b in zip(table, R) if a == b) / ROWS, 6)}


def candidates(salt):
    R = truth_table(salt)
    return [candidate(salt, j, R) for j in range(CANDIDATES)]


def partition(salt):
    o = rank(salt, "partition", range(ROWS))
    return sorted(o[:P_N]), sorted(o[P_N:P_N + H_N]), sorted(o[P_N + H_N:])


def acc(c, rows, R):
    t = c["table"]
    return round(sum(1 for r in rows if t[r] == R[r]) / len(rows), 6)


def run_world(salt):
    R = truth_table(salt)
    cands = candidates(salt)
    P, H, U = partition(salt)
    sel = sorted(rank(salt, "selection", P))[:SEL_N]
    pool = sorted(rank(salt, "confirmation", H))
    sc = {j: acc(cands[j], sel, R) for j in range(CANDIDATES)}
    order = sorted(range(CANDIDATES), key=lambda j: (-sc[j], j))
    full = [c["acc"] for c in cands]
    oracle = max(full)
    out = {}
    for arm in MEMORY_ARMS:
        k = KS[arm]
        m = CONF_POOL // k
        conf = pool[:m]
        top = order[:k]
        cf = {j: acc(cands[j], conf, R) for j in top}
        j = max(top, key=lambda x: (cf[x], -x))
        out[arm] = {"k": k, "rows_per_candidate": m, "promoted": j, "claimed": cf[j],
                    "true": full[j], "overclaim": round(cf[j] - full[j], 6),
                    "near_oracle": bool(full[j] >= oracle - 0.02),
                    "budget": CANDIDATES * SEL_N + m * k, "top": top,
                    "confirm_scores": {str(x): cf[x] for x in top}}
    best = max(range(CANDIDATES), key=lambda j: (full[j], -j))
    out["ORACLE"] = {"k": 0, "rows_per_candidate": 0, "promoted": best, "claimed": full[best],
                     "true": full[best], "overclaim": 0.0, "near_oracle": True, "budget": 0,
                     "top": [], "confirm_scores": {}}
    return {"arms": out, "oracle": oracle, "full": full, "cands": cands, "sel": sel, "pool": pool,
            "P": P, "H": H, "U": U, "sel_scores": sc}


def mean(xs):
    return round(sum(xs) / len(xs), 6)


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


def pubhex(a):
    return keypair(a).public_key().public_bytes(serialization.Encoding.Raw,
                                                serialization.PublicFormat.Raw).hex()


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


def verify_memory(entries, label):
    prev, bad, tenants, flags = "", [], set(), True
    for e in entries:
        tenants.add(e["tenant"])
        flags = flags and (not e["grants_authority"]) and (not e["executable"])
        body = canon({k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                        "nonce", "created_at", "grants_authority", "executable")})
        good = e["prev"] == prev and e["tenant"] == TENANT
        good = good and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"]
        good = good and e["nonce"] == nonce(e["agent"], e["kind"], e["key"], e["value"])
        if good:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubhex(e["agent"]))).verify(
                    bytes.fromhex(e["sig"]), body)
            except Exception:
                good = False
        if not good:
            bad.append(e["seq"])
        prev = e["hash"]
    return ok(f"memory {label}: chain+sigs", not bad), ok(f"memory {label}: tenant", tenants == {TENANT}), \
        ok(f"memory {label}: no-authority flags", flags)


def main():
    d = Path(sys.argv[1]).resolve()
    man = json.loads((d / "CBA_MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    ok("manifest signature", Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
        bytes.fromhex(man["signature"]), canon(body)) is None)
    files = {str(p.relative_to(d)): sha(p.read_bytes()) for p in sorted(d.rglob("*"))
             if p.is_file() and str(p.relative_to(d)) in man["files"]}
    ok("declared file hashes", files == man["files"])
    ok("merkle root", man["merkle_root"] == (d / "MERKLE_ROOT.txt").read_text().strip())
    ok("engine withheld", man.get("engine_withheld") is True)

    salts = json.loads((d / "SALTS.json").read_text())
    report = json.loads((d / "CBA_RUN_REPORT.json").read_text())
    worlds_pub = json.loads((d / "CBA_WORLDS.json").read_text())
    memory = json.loads((d / "CBA_MEMORY.json").read_text())
    for k, v in salts.items():
        ok(f"salt commitment {k}", report["salts"][k] == sha(v.encode()))

    derived = {}
    for label in ("salt1", "salt2"):
        base = salts[label]
        ws = []
        for w in range(WORLDS):
            salt = sha(f"{base}|world|{w}".encode())
            world = run_world(salt)
            ws.append(world)
            for a in MEMORY_ARMS:
                pub = worlds_pub[label][a][w]
                dd = world["arms"][a]
                ok(f"{label} w{w} {a} world", pub["promoted"] == dd["promoted"] and pub["claimed"] == dd["claimed"]
                   and pub["true"] == dd["true"])
        summary = {a: {"overclaim_mean": mean([w["arms"][a]["overclaim"] for w in ws]),
                       "true_mean": mean([w["arms"][a]["true"] for w in ws]),
                       "near_oracle_rate": round(sum(1 for w in ws if w["arms"][a]["near_oracle"]) / len(ws), 6)}
                   for a in ARMS}
        for a in ARMS:
            r = report["measures"][label][a]
            for f in ("overclaim_mean", "true_mean", "near_oracle_rate"):
                ok(f"{label} {a} {f}", abs(r[f] - summary[a][f]) < 1e-9)
        derived[label] = summary
        for a in MEMORY_ARMS:
            verify_memory(memory[label][a], f"{label}:{a}")
            ok(f"{label} {a} entry count", len(memory[label][a]) == report["memory"][label][a]["entries"])
            by = {}
            for e in memory[label][a]:
                if e["kind"] == "promotion":
                    by[e["value"]["world"]] = e["value"]
            good = True
            for w, world in enumerate(ws):
                dd = world["arms"][a]
                v = by.get(w)
                good = good and v is not None and v["promoted"] == dd["promoted"] \
                    and v["claimed"] == dd["claimed"] and v["k"] == dd["k"]
            ok(f"{label} {a} promotions", good)
            claims = {}
            for e in memory[label][a]:
                if e["kind"] == "claim":
                    claims[(e["value"]["world"], e["value"]["agent"])] = e["value"]["scores"]
            good = True
            for w, world in enumerate(ws):
                ex = world["sel_scores"]
                for i, agent in enumerate(AGENT_IDS):
                    got = claims.get((w, agent))
                    if got is None:
                        good = False
                        continue
                    for j in range(i * PER_AGENT, (i + 1) * PER_AGENT):
                        if got.get(str(j)) != ex[j]:
                            good = False
            ok(f"{label} {a} claims match", good)

    # recompute hypotheses
    S = derived
    H = report["hypotheses"]
    ok("H1 rule", all(S[s]["TOP8"]["overclaim_mean"] >= S[s]["TOP2"]["overclaim_mean"] + 0.08 for s in S)
       == H["H1_spreading_inflates_the_claim"]["ok"])
    ok("H2 rule", all(S[s]["TOP1"]["overclaim_mean"] <= 0.03 and S[s]["TOP2"]["overclaim_mean"] <= 0.04 for s in S)
       == H["H2_concentration_is_honest"]["ok"])
    ok("H3 rule", all(max(S[s]["TOP6"]["true_mean"], S[s]["TOP8"]["true_mean"]) <=
                      max(S[s]["TOP2"]["true_mean"], S[s]["TOP3"]["true_mean"]) + 0.005 for s in S)
       == H["H3_spreading_buys_no_capability"]["ok"])
    ok("H4 rule", all(max(S[s]["TOP2"]["true_mean"], S[s]["TOP3"]["true_mean"]) >= S[s]["TOP1"]["true_mean"] for s in S)
       == H["H4_two_or_three_beats_one"]["ok"])
    computed = {
        "H1_spreading_inflates_the_claim": all(S[s]["TOP8"]["overclaim_mean"] >= S[s]["TOP2"]["overclaim_mean"] + 0.08 for s in S),
        "H2_concentration_is_honest": all(S[s]["TOP1"]["overclaim_mean"] <= 0.03 and S[s]["TOP2"]["overclaim_mean"] <= 0.04 for s in S),
        "H3_spreading_buys_no_capability": all(max(S[s]["TOP6"]["true_mean"], S[s]["TOP8"]["true_mean"]) <=
                                               max(S[s]["TOP2"]["true_mean"], S[s]["TOP3"]["true_mean"]) + 0.005 for s in S),
        "H4_two_or_three_beats_one": all(max(S[s]["TOP2"]["true_mean"], S[s]["TOP3"]["true_mean"]) >= S[s]["TOP1"]["true_mean"] for s in S),
        "H5_integrity_and_no_authority": H["H5_integrity_and_no_authority"]["ok"],
    }
    for k, v in computed.items():
        ok(f"{k} ok", H[k]["ok"] == v)
        ok(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ok("H6 blocked", H["H6_external_review"]["verdict"] == "BLOCKED")
    core = all(H[k]["ok"] for k in H if k != "H6_external_review")
    ok("verdict", report["verdict"] == ("CONFIRMATION_ALLOCATION_SUPPORTED" if core else "NOT_SUPPORTED"))

    passed = sum(1 for _, good in CHECKS if good)
    for name, good in CHECKS:
        if not good:
            print("FAIL", name)
    print(f"{passed}/{len(CHECKS)} checks passed")
    return 0 if passed == len(CHECKS) else 1


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