#!/usr/bin/env python3
"""TRB standalone auditor — re-derives the tie-break study from the revealed salts. No CAIN imports."""
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 = 9
ROWS = 512
CANDIDATES = 40
AGENTS = 4
PER_AGENT = 10
EXAM_N = 12
CONF_N = 80
CLONES = 19
WORLDS = 12
ARMS = ("FIRST", "LAST", "RANDOM", "CONFIRM", "ORACLE")
MEMORY_ARMS = ARMS[:-1]
TENANT, SEED = "cain42-trb", "trb"
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 dnf(salt, key):
    terms = []
    for t in range(3):
        feats, vals, j = [], [], 0
        while len(feats) < 3:
            f = int(hashlib.sha256(f"{salt}|{key}|{t}|{j}".encode()).hexdigest()[:2], 16) % FEATURES
            if f not in feats:
                feats.append(f)
                vals.append(int(hashlib.sha256(f"{salt}|{key}|{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 exam_confirm(salt):
    o = rank(salt, "rows", range(ROWS))
    return sorted(o[:EXAM_N]), sorted(o[EXAM_N:EXAM_N + CONF_N])


def build_pool(salt, layout):
    truth = dnf(salt, "truth")
    exam, _ = exam_confirm(salt)
    ex = set(exam)
    clones = []
    for k in range(CLONES):
        rate = 0.22 + 0.06 * ((k % 5) / 4)
        clones.append(tuple(
            truth[r] if r in ex else
            (1 - truth[r] if ((int.from_bytes(hashlib.sha256(f"{salt}|cl{k}|{r}".encode()).digest()[:8], "big")
                               / 2 ** 64) < rate) else truth[r]) for r in range(ROWS)))
    honest = [dnf(salt, f"h{i}") for i in range(CANDIDATES - CLONES - 1)]
    if layout == "first":
        return clones + honest + [truth], truth, set(range(CLONES))
    return [truth] + honest + clones, truth, set(range(CANDIDATES - CLONES, CANDIDATES))


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


def full(t, truth):
    return round(sum(1 for a, b in zip(t, truth) if a == b) / ROWS, 6)


def run_world(salt):
    exam, conf = exam_confirm(salt)
    out = {}
    for arm in ARMS:
        layout = "last" if arm == "LAST" else "first"
        pool, truth, clones = build_pool(salt, layout)
        scores = [acc(t, exam, truth) for t in pool]
        mx = max(scores)
        tie = [j for j, x in enumerate(scores) if x == mx]
        if arm == "FIRST":
            j, claimed = min(tie), scores[min(tie)]
        elif arm == "LAST":
            j, claimed = max(tie), scores[max(tie)]
        elif arm == "RANDOM":
            j = min(tie, key=lambda x: sha(f"{salt}|tie|{x}".encode()))
            claimed = scores[j]
        else:
            j = max(range(CANDIDATES), key=lambda x: (full(pool[x], truth), -x))
            claimed = full(pool[j], truth)
        true = full(pool[j], truth)
        out[arm] = {"promoted": j, "exam_score": scores[j], "claimed": claimed, "true": true,
                    "overclaim": round(claimed - true, 6), "captured": bool(j in clones),
                    "tie_size": len(tie), "tie": tie, "layout": layout}
    pool, truth, clones = build_pool(salt, "first")
    scores = [acc(t, exam, truth) for t in pool]
    mx = max(scores)
    tie = [j for j, x in enumerate(scores) if x == mx]
    cf = {j: acc(pool[j], conf, truth) for j in tie}
    j = max(tie, key=lambda x: (cf[x], -x))
    true = full(pool[j], truth)
    out["CONFIRM"] = {"promoted": j, "exam_score": scores[j], "claimed": cf[j], "true": true,
                      "overclaim": round(cf[j] - true, 6), "captured": bool(j in clones),
                      "tie_size": len(tie), "tie": tie, "layout": "first",
                      "confirm_scores": {str(x): cf[x] for x in tie}}
    clone_true = round(sum(full(pool[i], truth) for i in sorted(clones)) / len(clones), 6)
    return {"arms": out, "tie_size": len(tie), "clone_true": clone_true}


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 / "TRB_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 / "TRB_RUN_REPORT.json").read_text())
    worlds_pub = json.loads((d / "TRB_WORLDS.json").read_text())
    memory = json.loads((d / "TRB_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((salt, world))
            for a in MEMORY_ARMS:
                pub = worlds_pub[label][a][w]
                dd = world["arms"][a]
                ok(f"{label} w{w} {a}", pub["promoted"] == dd["promoted"] and pub["claimed"] == dd["claimed"]
                   and pub["true"] == dd["true"] and bool(pub["captured"]) == dd["captured"])
        summary = {}
        for a in ARMS:
            vals = [w["arms"][a] for _, w in ws]
            summary[a] = {"capture_rate": round(sum(1 for v in vals if v["captured"]) / len(vals), 6),
                          "true_mean": mean([v["true"] for v in vals]),
                          "overclaim_mean": mean([v["overclaim"] for v in vals]),
                          "claimed_mean": mean([v["claimed"] for v in vals]),
                          "tie_size_mean": mean([v["tie_size"] for v in vals])}
        summary["_clone_true"] = mean([w["clone_true"] for _, w in ws])
        for a in ARMS:
            for f in ("capture_rate", "true_mean", "overclaim_mean", "claimed_mean", "tie_size_mean"):
                ok(f"{label} {a} {f}", abs(report["measures"][label][a][f] - summary[a][f]) < 1e-9)
        ok(f"{label} clone_true", abs(report["measures"][label]["_clone_true"] - summary["_clone_true"]) < 1e-9)
        derived[label] = summary
        for a in MEMORY_ARMS:
            verify_memory(memory[label][a], f"{label}:{a}")
            ok(f"{label} {a} entries", len(memory[label][a]) == report["memory"][label][a]["entries"])
            prom = {}
            for e in memory[label][a]:
                if e["kind"] == "promotion":
                    prom[e["value"]["world"]] = e["value"]
            good = True
            for w, (_, world) in enumerate(ws):
                dd = world["arms"][a]
                v = prom.get(w)
                good = good and v is not None and v["promoted"] == dd["promoted"] \
                    and v["claimed"] == dd["claimed"] and bool(v["captured"]) == dd["captured"]
            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, (salt, world) in enumerate(ws):
                layout = world["arms"][a]["layout"]
                pool, truth, _ = build_pool(salt, layout)
                exam, _ = exam_confirm(salt)
                sc = [acc(t, exam, truth) for t in pool]
                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)) != sc[j]:
                            good = False
            ok(f"{label} {a} claims", good)

    H = report["hypotheses"]
    S = derived
    computed = {
        "H1_deterministic_tiebreak_captured": all(
            S[s]["FIRST"]["capture_rate"] >= 0.90 and S[s]["LAST"]["capture_rate"] >= 0.90 and
            max(S[s]["FIRST"]["true_mean"], S[s]["LAST"]["true_mean"]) <= 0.85 and
            min(S[s]["FIRST"]["overclaim_mean"], S[s]["LAST"]["overclaim_mean"]) >= 0.15 for s in S),
        "H2_random_tiebreak_often_captured": all(S[s]["RANDOM"]["capture_rate"] >= 0.70 for s in S),
        "H3_fresh_confirmation_resolves_the_tie": all(
            S[s]["CONFIRM"]["capture_rate"] == 0.0 and S[s]["CONFIRM"]["true_mean"] >= 0.98 and
            S[s]["CONFIRM"]["overclaim_mean"] <= 0.03 for s in S),
        "H4_ties_are_not_evidence": all(S[s]["_clone_true"] <= 0.85 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"] == ("TIEBREAK_CAPTURE_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())
