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

Rebuilds the truth, forty candidates, the 12 selection blocks and 8 escrow sets, all seven arms over
2 salts x 12 worlds x 12 generations, every exam score, promotion, carry, overclaim and hypothesis;
then verifies the signed manifest, file hashes and Merkle root, the salt commitments, the published
worlds/partition, every Ed25519 signature and SHA-256 link of the governed memories, and the
exhaustion probe.

Usage: python3 verify_esr_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 = 11
ROWS = 2048
CANDIDATES = 40
AGENTS = 4
PER_AGENT = 10
SELN = 36
GENERATIONS = 12
CONF_N = 80
CONF_SETS = 8
TOP_K = 3
BUDGET = 1440
WORLDS = 12
ARMS = ("REUSE", "ROTATE", "ACCUMULATE", "CONFIRM", "CONFIRM_REUSE", "CONFIRM_STOP", "ORACLE")
MEMORY_ARMS = ARMS[:-1]
TENANT, SEED = "cain42-esr", "esr"
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, "rows", range(ROWS))
    sel = [sorted(o[i * SELN:(i + 1) * SELN]) for i in range(GENERATIONS)]
    base = GENERATIONS * SELN
    conf = [sorted(o[base + i * CONF_N:base + (i + 1) * CONF_N]) for i in range(CONF_SETS)]
    used = set(r for b in sel for r in b) | set(r for c in conf for r in c)
    return sel, conf, sorted(r for r in range(ROWS) if r not in used)


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


def run_world(salt):
    R = truth_table(salt)
    cands = candidates(salt)
    sel, conf, untouched = partition(salt)
    full = [c["acc"] for c in cands]
    oracle = max(full)
    out = {a: [] for a in ARMS}
    sc = [acc(c, sel[0], R) for c in cands]
    p = max(range(CANDIDATES), key=lambda j: (sc[j], -j))
    out["REUSE"] = [{"gen": g, "promoted": p, "claimed": sc[p], "true": full[p], "budget": BUDGET,
                     "carried": False, "exam": "reused:0", "confirm": None, "top": None}
                    for g in range(GENERATIONS)]
    for g in range(GENERATIONS):
        s = [acc(c, sel[g], R) for c in cands]
        j = max(range(CANDIDATES), key=lambda k: (s[k], -k))
        out["ROTATE"].append({"gen": g, "promoted": j, "claimed": s[j], "true": full[j], "budget": BUDGET,
                              "carried": False, "exam": f"rotate:{g}", "confirm": None, "top": None})
    sums = [0.0] * CANDIDATES
    for g in range(GENERATIONS):
        for j in range(CANDIDATES):
            sums[j] += acc(cands[j], sel[g], R)
        means = [sums[j] / (g + 1) for j in range(CANDIDATES)]
        j = max(range(CANDIDATES), key=lambda k: (means[k], -k))
        out["ACCUMULATE"].append({"gen": g, "promoted": j, "claimed": round(means[j], 6), "true": full[j],
                                  "budget": BUDGET, "carried": False, "exam": f"accumulate:0..{g}",
                                  "confirm": None, "top": None})
    a_reuse, a_stop, a_confirm = [], [], []
    last = None
    for g in range(GENERATIONS):
        if g < CONF_SETS:
            rows = sel[g][:30]
            s = [acc(c, rows, R) for c in cands]
            top = sorted(range(CANDIDATES), key=lambda j: (-s[j], j))[:TOP_K]
            cf = {j: acc(cands[j], conf[g], R) for j in top}
            j = max(top, key=lambda k: (cf[k], -k))
            rec = {"gen": g, "promoted": j, "claimed": cf[j], "true": full[j], "budget": BUDGET,
                   "carried": False, "exam": f"select:{g}", "confirm": f"escrow:{g}",
                   "top": top, "confirm_scores": {str(k): v for k, v in cf.items()}}
            last = rec
            a_reuse.append(dict(rec))
            a_stop.append(dict(rec))
            a_confirm.append(dict(rec))
        else:
            exam = conf[g - CONF_SETS][:36]
            s = [acc(c, exam, R) for c in cands]
            j = max(range(CANDIDATES), key=lambda k: (s[k], -k))
            a_reuse.append({"gen": g, "promoted": j, "claimed": s[j], "true": full[j], "budget": BUDGET,
                            "carried": False, "exam": f"reuse-escrow:{g - CONF_SETS}", "confirm": None,
                            "top": None, "exhausted": True})
            a_stop.append({"gen": g, "promoted": last["promoted"], "claimed": last["claimed"],
                           "true": last["true"], "budget": 0, "carried": True, "exam": "exhausted",
                           "confirm": None, "top": None, "exhausted": True})
            a_confirm.append({"gen": g, "promoted": None, "claimed": None, "true": None, "budget": 0,
                              "carried": True, "exam": "not_claimed", "confirm": None, "top": None})
    out["CONFIRM"] = a_confirm
    out["CONFIRM_REUSE"] = a_reuse
    out["CONFIRM_STOP"] = a_stop
    best = max(range(CANDIDATES), key=lambda j: (full[j], -j))
    out["ORACLE"] = [{"gen": g, "promoted": best, "claimed": full[best], "true": full[best], "budget": 0,
                      "carried": False, "exam": "oracle", "confirm": None, "top": None}
                     for g in range(GENERATIONS)]
    for a in ARMS:
        for r in out[a]:
            if r["claimed"] is not None:
                r["overclaim"] = round(r["claimed"] - r["true"], 6)
                r["regret"] = round(oracle - r["true"], 6)
    return {"arms": out, "oracle": oracle, "full": full, "cands": cands, "sel": sel, "conf": conf,
            "untouched": untouched}


def exam_scores(salt, world, arm, g):
    cands, sel, conf, R = world["cands"], world["sel"], world["conf"], truth_table(salt)
    if arm == "REUSE":
        rows = sel[0]
    elif arm == "ROTATE":
        rows = sel[g]
    elif arm == "ACCUMULATE":
        sums = [0.0] * CANDIDATES
        for gg in range(g + 1):
            for j in range(CANDIDATES):
                sums[j] += acc(cands[j], sel[gg], R)
        return {str(j): round(sums[j] / (g + 1), 6) for j in range(CANDIDATES)}
    elif arm in ("CONFIRM", "CONFIRM_STOP"):
        rows = sel[g][:30] if g < CONF_SETS else None
    elif arm == "CONFIRM_REUSE":
        rows = sel[g][:30] if g < CONF_SETS else conf[g - CONF_SETS][:36]
    else:
        rows = None
    return {str(j): acc(cands[j], rows, R) for j in range(CANDIDATES)} if rows is not None else None


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


def summarize(worlds):
    out = {}
    for a in ARMS:
        out[a] = []
        for g in range(GENERATIONS):
            vals = [w["arms"][a][g] for w in worlds]
            cl = [v["claimed"] for v in vals if v["claimed"] is not None]
            tr = [v["true"] for v in vals if v["true"] is not None]
            ov = [v["overclaim"] for v in vals if v.get("overclaim") is not None]
            out[a].append({"gen": g, "claimed_mean": mean(cl), "true_mean": mean(tr),
                           "overclaim_mean": mean(ov), "claimed_count": len(cl),
                           "budget_mean": mean([v["budget"] for v in vals]),
                           "carried_count": sum(1 for v in vals if v.get("carried"))})
        out[a].append({"gen": "summary", "overclaim_gen11": out[a][-1]["overclaim_mean"],
                       "true_gen11": out[a][-1]["true_mean"],
                       "overclaim_0_7": mean([r["overclaim_mean"] for r in out[a][:8] if r["overclaim_mean"] is not None]),
                       "overclaim_8_11": mean([r["overclaim_mean"] for r in out[a][8:] if r["overclaim_mean"] is not None]),
                       "true_mean": mean([r["true_mean"] for r in out[a][:GENERATIONS] if r["true_mean"] is not None])})
    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 / "ESR_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 / "ESR_RUN_REPORT.json").read_text())
    worlds_pub = json.loads((d / "ESR_WORLDS.json").read_text())
    part_pub = json.loads((d / "ESR_PARTITION.json").read_text())
    memory = json.loads((d / "ESR_MEMORY.json").read_text())
    for k, v in salts.items():
        ok(f"salt commitment {k}", report["salts"][k] == sha(v.encode()))

    derived, derived_worlds = {}, {}
    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))
            sel, conf, untouched = world["sel"], world["conf"], world["untouched"]
            p = part_pub[label][w]
            ok(f"{label} w{w} partition", p["select_blocks"] == sel and p["confirm_sets"] == conf
               and p["untouched_count"] == len(untouched))
            ok(f"{label} w{w} escrow disjoint",
               all(len(set(b) & set(c)) == 0 for b in sel for c in conf))
        derived_worlds[label] = ws
        summary = summarize([w for _, w in ws])
        derived[label] = summary
        for a in ARMS:
            for g in range(GENERATIONS):
                r, dd = report["measures"][label][a][g], summary[a][g]
                if abs((r["overclaim_mean"] or 0) - (dd["overclaim_mean"] or 0)) > 1e-9:
                    ok(f"{label} {a} g{g} overclaim", False)
                if abs((r["true_mean"] or 0) - (dd["true_mean"] or 0)) > 1e-9:
                    ok(f"{label} {a} g{g} true", False)
            for field in ("overclaim_gen11", "true_gen11", "overclaim_0_7", "overclaim_8_11", "true_mean"):
                rv = report["measures"][label][a][-1][field]
                dv = summary[a][-1][field]
                same = (rv is None and dv is None) or (rv is not None and dv is not None and abs(rv - dv) < 1e-9)
                ok(f"{label} {a} {field}", same)
        # published worlds: promotions and claims
        for w, (salt, world) in enumerate(ws):
            pub = worlds_pub[label]["arms"]
            same = True
            for a in ARMS:
                for g in range(GENERATIONS):
                    r = pub[a][w][g]
                    dd = world["arms"][a][g]
                    same = same and r["promoted"] == dd["promoted"] and r["claimed"] == dd["claimed"] \
                        and r["true"] == dd["true"] and bool(r.get("carried")) == bool(dd.get("carried"))
            ok(f"{label} w{w} published promotions", same)
            camp = {a: [{"promoted": world["arms"][a][g]["promoted"],
                         "claimed": world["arms"][a][g]["claimed"]} for g in range(GENERATIONS)] for a in ARMS}
            ok(f"{label} w{w} oracle", abs(world["oracle"] - max(world["full"])) < 1e-12)

    # memory: chain, counts, and every generation's promotion / agent claim
    for label in ("salt1", "salt2"):
        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" and not e["value"].get("carried"):
                    by[(e["value"]["world"], e["value"]["gen"])] = e["value"]
            good = True
            for w, (salt, world) in enumerate(derived_worlds[label]):
                for g in range(GENERATIONS):
                    dd = world["arms"][a][g]
                    if dd["promoted"] is None:
                        continue
                    if dd.get("carried"):
                        continue
                    v = by.get((w, g))
                    good = good and v is not None and v["promoted"] == dd["promoted"] \
                        and v["claimed"] == dd["claimed"]
            ok(f"{label} {a} promotions match", good)
            claims = {}
            for e in memory[label][a]:
                if e["kind"] == "claim":
                    claims[(e["value"]["world"], e["value"]["gen"], e["agent"])] = e["value"]["scores"]
            good = True
            for w, (salt, world) in enumerate(derived_worlds[label]):
                for g in range(GENERATIONS):
                    dd = world["arms"][a][g]
                    if dd["promoted"] is None or dd.get("carried"):
                        continue
                    ex = exam_scores(salt, world, a, g)
                    for i, agent in enumerate(AGENT_IDS):
                        got = claims.get((w, g, 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[str(j)]:
                                good = False
            ok(f"{label} {a} claims match", good)

    H = report["hypotheses"]
    S = derived
    for s in S:
        pass
    ok("H1 rule", all(S[s]["REUSE"][-1]["overclaim_gen11"] >= 0.08 and S[s]["ROTATE"][-1]["overclaim_gen11"] >= 0.08
                      for s in S) == H["H1_a_single_exam_stays_biased"]["ok"])
    ok("H2 rule", all(S[s]["ACCUMULATE"][-1]["overclaim_gen11"] <= 0.05 and
                      S[s]["ROTATE"][-1]["overclaim_gen11"] - S[s]["ACCUMULATE"][-1]["overclaim_gen11"] >= 0.06
                      for s in S) == H["H2_accumulation_fixes_selection"]["ok"])
    ok("H3 rule", all(all((r["overclaim_mean"] is not None and r["overclaim_mean"] <= 0.06)
                          for r in S[s]["CONFIRM"][:CONF_SETS]) for s in S)
       == H["H3_fresh_confirmation_is_honest"]["ok"])
    ok("H4 rule", all(S[s]["CONFIRM_REUSE"][-1]["overclaim_8_11"] >= 0.08 and
                      S[s]["CONFIRM_REUSE"][-1]["overclaim_8_11"] >= S[s]["CONFIRM_REUSE"][-1]["overclaim_0_7"] + 0.04
                      for s in S) == H["H4_reusing_exhausted_escrow_rebiases"]["ok"])
    ok("H5 rule", all(all((r["overclaim_mean"] is not None and r["overclaim_mean"] <= 0.06)
                          for r in S[s]["CONFIRM_STOP"][8:GENERATIONS]) and
                      abs(S[s]["CONFIRM_STOP"][-1]["true_gen11"] - S[s]["CONFIRM_REUSE"][-1]["true_gen11"]) <= 0.02
                      for s in S) == H["H5_stopping_beats_reusing"]["ok"])
    computed = {
        "H1_a_single_exam_stays_biased": all(
            S[s]["REUSE"][-1]["overclaim_gen11"] >= 0.08 and S[s]["ROTATE"][-1]["overclaim_gen11"] >= 0.08 for s in S),
        "H2_accumulation_fixes_selection": all(
            S[s]["ACCUMULATE"][-1]["overclaim_gen11"] <= 0.05 and
            S[s]["ROTATE"][-1]["overclaim_gen11"] - S[s]["ACCUMULATE"][-1]["overclaim_gen11"] >= 0.06 for s in S),
        "H3_fresh_confirmation_is_honest": all(
            all((r["overclaim_mean"] is not None and r["overclaim_mean"] <= 0.06) for r in S[s]["CONFIRM"][:CONF_SETS])
            for s in S),
        "H4_reusing_exhausted_escrow_rebiases": all(
            S[s]["CONFIRM_REUSE"][-1]["overclaim_8_11"] >= 0.08 and
            S[s]["CONFIRM_REUSE"][-1]["overclaim_8_11"] >= S[s]["CONFIRM_REUSE"][-1]["overclaim_0_7"] + 0.04 for s in S),
        "H5_stopping_beats_reusing": all(
            all((r["overclaim_mean"] is not None and r["overclaim_mean"] <= 0.06)
                for r in S[s]["CONFIRM_STOP"][8:GENERATIONS]) and
            abs(S[s]["CONFIRM_STOP"][-1]["true_gen11"] - S[s]["CONFIRM_REUSE"][-1]["true_gen11"]) <= 0.02
            for s in S),
        "H6_integrity_escrow_and_no_authority": H["H6_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("H7 blocked", H["H7_external_review"]["verdict"] == "BLOCKED")
    core = all(H[k]["ok"] for k in H if k != "H7_external_review")
    ok("verdict", report["verdict"] == ("ESCROW_LIFECYCLE_SUPPORTED" if core else "NOT_SUPPORTED"))

    # exhaustion probe: the reused exam is a previously used confirmation set
    for label in ("salt1", "salt2"):
        salt = sha(f"{salts[label]}|world|0".encode())
        sel, conf, _ = partition(salt)
        reused = set(conf[0][:36])
        ok(f"{label} reuse is not fresh", len(reused & set(sel[0])) == 0 and reused <= set(conf[0]))

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