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

Rebuilds the truth, forty candidates, the public/escrow/untouched partition, all six arms over
2 salts x 12 worlds, every score, promotion, overclaim, regret and hypothesis; then verifies the
signed manifest, every file hash and Merkle root, the salt commitments, every Ed25519 signature and
SHA-256 link of the exported governed memories, and the escrow-substitution probe.

Usage: python3 verify_tse_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 = CANDIDATES // AGENTS
P_N, H_N, U_N = 128, 112, 16
WORLDS = 12
SEL_N, TOP_K, CONFIRM_N, SINGLE_N = 12, 5, 96, 24
ARMS = ("PROPOSER", "RANDOM", "ESCROW", "ESCROW_CONFIRM", "TRUST", "ORACLE")
MEMORY_ARMS = ("PROPOSER", "RANDOM", "ESCROW", "ESCROW_CONFIRM", "TRUST")
TENANT, SEED = "cain42-tse", "tse"
AGENT_IDS = tuple(f"agent{i}" for i in range(AGENTS))
SIGNERS = AGENT_IDS + ("verifier", "insider")
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)))
    table = []
    for r in range(ROWS):
        table.append(1 if any(all(bit(r, f) == v for f, v in zip(fs, vs)) for fs, vs in terms) else 0)
    return tuple(table)


def support(salt, j):
    h = hashlib.sha256(f"{salt}|support|{j}".encode()).digest()
    fa = h[0] % FEATURES
    fb = (fa + 1 + h[1] % (FEATURES - 1)) % FEATURES
    return (fa, fb, h[2] & 1, h[3] & 1), [r for r in range(ROWS) if bit(r, fa) == (h[2] & 1)
                                          and bit(r, fb) == (h[3] & 1)]


def candidate(salt, j, R):
    _, inside = support(salt, j)
    h = hashlib.sha256(f"{salt}|cand|{j}".encode()).digest()
    d_in = 0.02 + 0.08 * (int.from_bytes(h[4:12], "big") / 2 ** 64)
    d_out = 0.22 + 0.22 * (int.from_bytes(h[12:20], "big") / 2 ** 64)
    in_set = set(inside)
    table = []
    for r in range(ROWS):
        d = d_in if r in in_set 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 {"j": j, "table": table,
            "acc": round(sum(1 for a, b in zip(table, R) if a == b) / ROWS, 6),
            "d_in": d_in, "d_out": d_out}


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


def part(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):
    return round(sum(1 for r in rows if c["table"][r] == R[r]) / len(rows), 6)


def prop_rows(salt, j, public):
    _, inside = support(salt, j)
    inside = set(inside)
    avail = rank(salt, f"prop|{j}", [r for r in public if r in inside])
    if len(avail) < 24:
        avail += rank(salt, f"propfill|{j}", [r for r in public if r not in inside])
    return sorted(avail[:24])


def rand_rows(salt, j, public):
    return sorted(rank(salt, f"rand|{j}", public)[:24])


def esc_rows(salt, escrow, n, off=0, tag="esc"):
    return sorted(rank(salt, tag, escrow))[off:off + n]


def insider(salt, cands):
    return max(range(CANDIDATES), key=lambda j: (cands[j]["d_out"] - cands[j]["d_in"], -j))


def run_arm(salt, arm, R, cands):
    public, escrow, untouched = part(salt)
    if arm in ("PROPOSER", "RANDOM", "ESCROW"):
        rows = ({j: prop_rows(salt, j, public) for j in range(CANDIDATES)} if arm == "PROPOSER" else
                {j: rand_rows(salt, j, public) for j in range(CANDIDATES)} if arm == "RANDOM" else
                {j: esc_rows(salt, escrow, SINGLE_N) for j in range(CANDIDATES)})
        scores = {j: acc(cands[j], rows[j], R) for j in rows}
        promoted = max(range(CANDIDATES), key=lambda j: (scores.get(j, -1.0), -j))
        apparent = scores[promoted]
        budget = CANDIDATES * SINGLE_N
    elif arm == "ESCROW_CONFIRM":
        rows = {j: esc_rows(salt, escrow, SEL_N) for j in range(CANDIDATES)}
        scores = {j: acc(cands[j], rows[j], R) for j in rows}
        top = sorted(range(CANDIDATES), key=lambda j: (-scores[j], j))[:TOP_K]
        conf_rows = esc_rows(salt, escrow, CONFIRM_N, off=SEL_N, tag="conf")
        conf = {j: acc(cands[j], conf_rows, R) for j in top}
        promoted = max(top, key=lambda j: (conf[j], -j))
        apparent = conf[promoted]
        budget = CANDIDATES * SEL_N + TOP_K * CONFIRM_N
    elif arm == "TRUST":
        promoted = insider(salt, cands)
        apparent = 0.99
        rows = {promoted: []}
        budget = 0
    else:
        promoted = max(range(CANDIDATES), key=lambda j: (cands[j]["acc"], -j))
        apparent = cands[promoted]["acc"]
        rows = {}
        budget = 0
    true = cands[promoted]["acc"]
    oracle = max(c["acc"] for c in cands)
    return {"promoted": promoted, "apparent": round(apparent, 6), "true_acc": true,
            "oracle_true": oracle, "budget": budget,
            "overclaim": round(apparent - true, 6), "regret": round(oracle - true, 6),
            "poor": bool(true < oracle - 0.03), "scores": {}, "rows": rows}


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


def summarize(all_world):
    out = {}
    for a, rows in all_world.items():
        out[a] = {"true_mean": mean([x["true_acc"] for x in rows]),
                  "overclaim_mean": mean([x["overclaim"] for x in rows]),
                  "regret_mean": mean([x["regret"] for x in rows]),
                  "apparent_mean": mean([x["apparent"] for x in rows]),
                  "poor_rate": round(sum(1 for x in rows if x["poor"]) / len(rows), 6),
                  "budget_mean": mean([x["budget"] for x in rows])}
    return out


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 / "TSE_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 / "TSE_RUN_REPORT.json").read_text())
    for k, v in salts.items():
        ok(f"salt commitment {k}", report["salts"][k] == sha(v.encode()))

    memory = json.loads((d / "TSE_MEMORY.json").read_text())
    rows_pub = json.loads((d / "TSE_ROWS.json").read_text())
    conf_pub = json.loads((d / "TSE_CONFIRM.json").read_text())
    part_pub = json.loads((d / "TSE_PARTITION.json").read_text())
    derived = {}
    for label in ("salt1", "salt2"):
        base = salts[label]
        worlds = {a: [] for a in ARMS}
        for w in range(WORLDS):
            salt = sha(f"{base}|world|{w}".encode())
            R, cands = truth_table(salt), candidates(salt)
            for a in ARMS:
                worlds[a].append(run_arm(salt, a, R, cands))
        summary = summarize(worlds)
        derived[label] = summary
        for a in ARMS:
            r = report["measures"][label][a]
            ok(f"{label} {a} true", abs(r["true_mean"] - summary[a]["true_mean"]) < 1e-9)
            ok(f"{label} {a} overclaim", abs(r["overclaim_mean"] - summary[a]["overclaim_mean"]) < 1e-9)
            ok(f"{label} {a} poor", abs(r["poor_rate"] - summary[a]["poor_rate"]) < 1e-9)
        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"])
            # every promotion record must name the derived winner for its world
            prom = {}
            for e in memory[label][a]:
                if e["kind"] == "promotion":
                    prom[e["value"]["world"]] = e["value"]["candidate"]
            ok(f"{label} {a} promotions", len(prom) == WORLDS and
               all(prom[w] == worlds[a][w]["promoted"] for w in range(WORLDS)))

    # published evidence (rows, confirmation scores, partition) must match the salt-derived world
    for label in ("salt1", "salt2"):
        base = salts[label]
        for w in range(WORLDS):
            salt = sha(f"{base}|world|{w}".encode())
            R, cands = truth_table(salt), candidates(salt)
            P, H, U = part(salt)
            p = part_pub[label][str(w)]
            ok(f"{label} w{w} partition", sorted(p["public"]) == P and sorted(p["escrow"]) == H
               and sorted(p["untouched"]) == U
               and p["escrow_commitment"] == sha((",".join(map(str, H))).encode()))
            pub = rows_pub[label][str(w)]
            same = True
            for j in range(CANDIDATES):
                same = same and pub["PROPOSER"][str(j)] == prop_rows(salt, j, P)
                same = same and pub["RANDOM"][str(j)] == rand_rows(salt, j, P)
                same = same and pub["ESCROW"][str(j)] == esc_rows(salt, H, SINGLE_N)
                same = same and pub["ESCROW_CONFIRM"][str(j)] == esc_rows(salt, H, SEL_N)
            ok(f"{label} w{w} published rows", same)
            sel = {j: esc_rows(salt, H, SEL_N) for j in range(CANDIDATES)}
            se = {j: acc(cands[j], sel[j], R) for j in range(CANDIDATES)}
            top = sorted(range(CANDIDATES), key=lambda j: (-se[j], j))[:TOP_K]
            conf_rows = esc_rows(salt, H, CONFIRM_N, off=SEL_N, tag="conf")
            conf = conf_pub[label][str(w)]["ESCROW_CONFIRM"]
            ok(f"{label} w{w} confirmation scores", set(conf) == {str(j) for j in top} and
               all(abs(conf[str(j)] - acc(cands[j], conf_rows, R)) < 1e-9 for j in top))


    H = report["hypotheses"]
    S = derived
    ok("H1 rule", (all(S[s]["PROPOSER"]["overclaim_mean"] >= 0.15 and
                       S[s]["PROPOSER"]["true_mean"] <= S[s]["RANDOM"]["true_mean"] - 0.03 for s in S))
       == H["H1_agent_chosen_exam_inflates"]["ok"])
    ok("H2 rule", all(S[s]["RANDOM"]["overclaim_mean"] >= 0.05 for s in S)
       == H["H2_unbiased_selection_still_overclaims"]["ok"])
    ok("H3 rule", all(S[s]["ESCROW"]["overclaim_mean"] >= 0.05 for s in S)
       == H["H3_shared_escrow_still_overclaims"]["ok"])
    ok("H4 rule", all(S[s]["ESCROW_CONFIRM"]["overclaim_mean"] <= 0.03 for s in S)
       == H["H4_confirmation_certifies_the_score"]["ok"])
    ok("H5 rule", all(S[s]["ESCROW_CONFIRM"]["true_mean"] >= S[s]["ESCROW"]["true_mean"] + 0.015 and
                      S[s]["ESCROW_CONFIRM"]["true_mean"] >= 0.94 * S[s]["ORACLE"]["true_mean"] for s in S)
       == H["H5_confirmation_recovers_capability"]["ok"])
    ok("H6 rule", all(S[s]["TRUST"]["true_mean"] <= S[s]["ESCROW_CONFIRM"]["true_mean"] - 0.08 and
                      S[s]["TRUST"]["overclaim_mean"] >= 0.20 for s in S)
       == H["H6_signed_claim_is_not_evidence"]["ok"])
    computed = {
        "H1_agent_chosen_exam_inflates": all(S[s]["PROPOSER"]["overclaim_mean"] >= 0.15 and
                                             S[s]["PROPOSER"]["true_mean"] <= S[s]["RANDOM"]["true_mean"] - 0.03 for s in S),
        "H2_unbiased_selection_still_overclaims": all(S[s]["RANDOM"]["overclaim_mean"] >= 0.05 for s in S),
        "H3_shared_escrow_still_overclaims": all(S[s]["ESCROW"]["overclaim_mean"] >= 0.05 for s in S),
        "H4_confirmation_certifies_the_score": all(S[s]["ESCROW_CONFIRM"]["overclaim_mean"] <= 0.03 for s in S),
        "H5_confirmation_recovers_capability": all(
            S[s]["ESCROW_CONFIRM"]["true_mean"] >= S[s]["ESCROW"]["true_mean"] + 0.015 and
            S[s]["ESCROW_CONFIRM"]["true_mean"] >= 0.94 * S[s]["ORACLE"]["true_mean"] for s in S),
        "H6_signed_claim_is_not_evidence": all(
            S[s]["TRUST"]["true_mean"] <= S[s]["ESCROW_CONFIRM"]["true_mean"] - 0.08 and
            S[s]["TRUST"]["overclaim_mean"] >= 0.20 for s in S),
        "H7_integrity_escrow_and_no_authority": H["H7_integrity_escrow_and_no_authority"]["ok"],
    }
    for k, v in computed.items():
        ok(f"{k} ok flag", H[k]["ok"] == v)
        ok(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ok("H8 blocked", H["H8_external_review"]["verdict"] == "BLOCKED")
    core = all(H[k]["ok"] for k in H if k != "H8_external_review")
    ok("verdict", (report["verdict"] == ("TEST_SET_ESCROW_SUPPORTED" if core else "NOT_SUPPORTED")))

    # escrow substitution probe, recomputed for world 0 of each salt
    for label in ("salt1", "salt2"):
        salt = sha(f"{salts[label]}|world|0".encode())
        public, escrow, untouched = part(salt)
        rows = esc_rows(salt, escrow, SINGLE_N)
        committed = sha((",".join(map(str, rows))).encode())
        swapped = list(rows)
        swapped[0] = untouched[0]
        after = sha((",".join(map(str, sorted(swapped)))).encode())
        ok(f"{label} escrow substitution detected", committed != after)

    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())
