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

Rebuilds every world, every scan, every fresh / reused confirmation, the committed sets, all six arms,
every declaration and every hypothesis; then verifies the signed manifest, file hashes and Merkle root,
the salt commitments, the scan-vs-confirmation provenance, and every governed-memory signature.

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

import hashlib
import json
import math
import sys
from pathlib import Path

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

DESIGNS, DESIGN_ROWS = 12, 64
ROWS = DESIGNS * DESIGN_ROWS
BUDGET, COMMITTED, SCAN_ROWS, TOPUP, COMMIT_ROWS = 240, 8, 16, 48, 30
ALPHA = 0.01
CAMPAIGNS = 200
WORLDS = ("null", "global", "local")
ARMS = ("scan_only", "topup_fresh", "topup_reused", "committed_pool", "committed_best_bonf", "oracle")
MEMORY_ARMS = ARMS[:5]
TENANT, SEED = "cain42-exs", "exs"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"


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


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


def z_for(alpha):
    table = {0.01: 2.3263478740408408, 0.00125: 3.0233406170733936}
    if alpha in table:
        return table[alpha]
    p = 1.0 - alpha
    a_ = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02,
          1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00]
    b_ = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02,
          6.680131188771972e+01, -1.328068155288572e+01]
    c_ = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00,
          -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00]
    d_ = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00]
    if p < 0.02425:
        q = math.sqrt(-2 * math.log(p))
        return -(((((c_[0] * q + c_[1]) * q + c_[2]) * q + c_[3]) * q + c_[4]) * q + c_[5]) / \
               ((((d_[0] * q + d_[1]) * q + d_[2]) * q + d_[3]) * q + 1)
    q = p - 0.5
    r = q * q
    return (((((a_[0] * r + a_[1]) * r + a_[2]) * r + a_[3]) * r + a_[4]) * r + a_[5]) * q / \
           (((((b_[0] * r + b_[1]) * r + b_[2]) * r + b_[3]) * r + b_[4]) * r + 1)


def clears(k, n, alpha=ALPHA):
    if n <= 0:
        return False
    return (k / n - 0.5) / math.sqrt(0.25 / n) > z_for(alpha)


def local_design(salt, campaign):
    return int(hashlib.sha256(f"{salt}|local|{campaign}".encode()).hexdigest()[:8], 16) % DESIGNS


def committed_set(salt, campaign):
    order = sorted(range(DESIGNS), key=lambda d: hashlib.sha256(
        f"{salt}|commit|{campaign}|{d}".encode()).hexdigest())
    return sorted(order[:COMMITTED])


def world_rows(salt, world, campaign):
    ld = local_design(salt, campaign)
    bits = [0] * ROWS
    for d in range(DESIGNS):
        n_one = DESIGN_ROWS // 2
        if world == "global":
            n_one = 38
        elif world == "local" and d == ld:
            n_one = 58
        order = sorted(range(DESIGN_ROWS), key=lambda j: hashlib.sha256(
            f"{salt}|{world}|c{campaign}|d{d}|r{j}".encode()).hexdigest())
        for j in order[:n_one]:
            bits[d * DESIGN_ROWS + j] = 1
    return bits


def _order(salt, campaign, arm, d):
    return sorted(range(DESIGN_ROWS), key=lambda j: hashlib.sha256(
        f"{salt}|{campaign}|{arm}|d{d}|j{j}".encode()).hexdigest())


def _rows_for(salt, campaign, arm, d, n):
    return [d * DESIGN_ROWS + j for j in _order(salt, campaign, arm, d)[:n]]


def _true_positive(world, salt, campaign, d):
    return world == "global" or (world == "local" and d == local_design(salt, campaign))


def run_campaign(salt, world, arm, campaign):
    bits = world_rows(salt, world, campaign)
    reads, scan_rows, confirm_rows, fresh_rows = [], [], [], []
    declared, selected, correct = False, None, False
    if arm in ("scan_only", "topup_fresh", "topup_reused"):
        scan = []
        for d in range(DESIGNS):
            rows = _rows_for(salt, campaign, arm + "-scan", d, SCAN_ROWS)
            k = sum(bits[r] for r in rows)
            scan.append({"design": d, "k": k, "n": SCAN_ROWS})
            reads.append({"design": d, "n": SCAN_ROWS, "k": k, "rows": rows, "stage": "scan"})
        best = max(scan, key=lambda x: (x["k"] / x["n"], -x["design"]))["design"]
        scan_rows = _rows_for(salt, campaign, arm + "-scan", best, SCAN_ROWS)
        k_scan = sum(bits[r] for r in scan_rows)
        design_all = set(_rows_for(salt, campaign, arm + "-scan", best, DESIGN_ROWS))
        if arm == "scan_only":
            confirm_rows = list(scan_rows)
            k, n, alpha = k_scan, SCAN_ROWS, ALPHA
        elif arm == "topup_fresh":
            fresh_rows = sorted(design_all - set(scan_rows))
            confirm_rows = list(scan_rows) + list(fresh_rows)
            k, n, alpha = k_scan + sum(bits[r] for r in fresh_rows), SCAN_ROWS + TOPUP, ALPHA
        else:
            fresh_rows = [scan_rows[j % SCAN_ROWS] for j in range(TOPUP)]
            confirm_rows = list(scan_rows) + fresh_rows
            k, n, alpha = sum(bits[r] for r in confirm_rows), SCAN_ROWS + TOPUP, ALPHA
        reads.append({"design": best, "n": SCAN_ROWS + (TOPUP if arm != "scan_only" else 0),
                      "k": k, "rows": confirm_rows, "stage": "confirm"})
        selected = best
        declared = clears(k, n, alpha)
        correct = declared and _true_positive(world, salt, campaign, best)
        final = {"k": k, "n": n}
    elif arm == "committed_pool":
        cs = committed_set(salt, campaign)
        k_tot = n_tot = 0
        for d in cs:
            rows = _rows_for(salt, campaign, arm, d, COMMIT_ROWS)
            k = sum(bits[r] for r in rows)
            k_tot += k
            n_tot += len(rows)
            reads.append({"design": d, "n": len(rows), "k": k, "rows": rows, "stage": "commit"})
            confirm_rows.extend(rows)
        declared = clears(k_tot, n_tot, ALPHA)
        correct = declared and any(_true_positive(world, salt, campaign, d) for d in cs)
        selected = cs
        final = {"k": k_tot, "n": n_tot}
    elif arm == "committed_best_bonf":
        cs = committed_set(salt, campaign)
        scan = []
        for d in cs:
            rows = _rows_for(salt, campaign, arm, d, COMMIT_ROWS)
            k = sum(bits[r] for r in rows)
            scan.append({"design": d, "k": k, "n": len(rows)})
            reads.append({"design": d, "n": len(rows), "k": k, "rows": rows, "stage": "commit"})
            confirm_rows.extend(rows)
        best = max(scan, key=lambda x: (x["k"] / x["n"], -x["design"]))["design"]
        k, n = next((x["k"], x["n"]) for x in scan if x["design"] == best)
        declared = clears(k, n, ALPHA / COMMITTED)
        selected = best
        correct = declared and _true_positive(world, salt, campaign, best)
        final = {"k": k, "n": n}
    else:
        selected = (local_design(salt, campaign) if world == "local" else (0 if world == "global" else None))
        declared = world != "null"
        correct = declared
        final = {"k": 0, "n": 0}
    overlap = len(set(fresh_rows) & set(scan_rows)) if fresh_rows else 0
    return {"arm": arm, "world": world, "campaign": campaign, "declared": bool(declared),
            "selected": selected, "correct": bool(correct), "k": final["k"], "n": final["n"],
            "overlap": overlap, "reads": reads}


def main():
    if len(sys.argv) < 2:
        print("usage: verify_exs_offline.py <bundle-dir>")
        return 2
    d = Path(sys.argv[1])
    checks, fails = [], []

    def ck(n, ok):
        checks.append(n)
        if not ok:
            fails.append(n)

    man = json.loads((d / "MANIFEST.json").read_text())
    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)
    fs = sorted(p for p in d.rglob("*") if p.is_file()
                and p.name not in ("MANIFEST.json", "EXS_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                                   "EXS_OMEGA_SEAL.json", "EXS_PUBKEY.pem", "EXS_SIGNED_BODY.json")
                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")

    pre = json.loads((d / "EXS_PREREGISTRATION.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    ck("salt commitment", {k: sha(v.encode()) for k, v in sal.items()} == pre["salts_commitment"])
    ck("status line", pre["status"] == STATUS)
    ck("hypothesis set", set(pre["hypotheses"]) == {
        "H1_selection_and_fake_confirmation_inflate", "H2_commitment_or_correction_controls",
        "H3_pooling_wins_a_global_effect", "H4_fresh_confirmation_wins_a_local_effect",
        "H5_integrity_provenance_and_no_authority", "H6_external_review"})

    rep = json.loads((d / "EXS_RUN_REPORT.json").read_text())
    rows_file = json.loads((d / "EXS_ROWS.json").read_text())
    mem = json.loads((d / "EXS_MEMORY.json").read_text())

    sims = {s: {a: {w: [run_campaign(sal[s], w, a, i) for i in range(CAMPAIGNS)] for w in WORLDS}
                for a in ARMS} for s in sal}
    for s in sal:
        for a in ARMS:
            for w in WORLDS:
                got, sim = rows_file[s][a][w], sims[s][a][w]
                ck(f"rows {s}:{a}:{w}", len(got) == len(sim))
                bad = 0
                for g, r in zip(got, sim):
                    for key in ("declared", "correct", "selected", "k", "n", "overlap"):
                        if g.get(key) != r.get(key):
                            bad += 1
                            break
                ck(f"values {s}:{a}:{w}", bad == 0)

    def rate(s, a, w, key="declared"):
        return sum(1 for c in sims[s][a][w] if c[key]) / CAMPAIGNS

    H = rep["hypotheses"]
    ck("H1", all(rate(s, "scan_only", "null") > 0.02 and rate(s, "topup_reused", "null") > 0.40 for s in sal)
       and H["H1_selection_and_fake_confirmation_inflate"]["verdict"] == "SUPPORTED")
    ck("H2", all(rate(s, a, "null") <= 0.015 for s in sal
                 for a in ("topup_fresh", "committed_pool", "committed_best_bonf"))
       and H["H2_commitment_or_correction_controls"]["verdict"] == "SUPPORTED")
    ck("H3", all(rate(s, "committed_pool", "global", "correct") >= 0.65
                 and rate(s, "committed_pool", "global", "correct")
                 >= rate(s, "topup_fresh", "global", "correct") + 0.50 for s in sal)
       and H["H3_pooling_wins_a_global_effect"]["verdict"] == "SUPPORTED")
    ck("H4", all(rate(s, "topup_fresh", "local", "correct") >= 0.90
                 and rate(s, "topup_fresh", "local", "correct")
                 >= rate(s, "committed_pool", "local", "correct") + 0.50 for s in sal)
       and H["H4_fresh_confirmation_wins_a_local_effect"]["verdict"] == "SUPPORTED")
    h5 = H["H5_integrity_provenance_and_no_authority"]["detail"]
    ck("H5", all(h5[f"{s}:{a}"]["chain_and_signatures"] and h5[f"{s}:{a}"]["replay_refused"]
                 and h5[f"{s}:{a}"]["tamper_detected"] and h5[f"{s}:{a}"]["authority_from_memory_refused"]
                 and h5[f"{s}:{a}"]["authority_flag_false_everywhere"]
                 for s in sal for a in MEMORY_ARMS)
       and all(h5[f"{s}:provenance"]["fresh_overlap_campaigns"] == 0
               and h5[f"{s}:provenance"]["reused_overlap_campaigns"] == CAMPAIGNS for s in sal)
       and H["H5_integrity_provenance_and_no_authority"]["verdict"] == "SUPPORTED")
    core = all(H[k]["verdict"] == "SUPPORTED" for k in
               ("H1_selection_and_fake_confirmation_inflate", "H2_commitment_or_correction_controls",
                "H3_pooling_wins_a_global_effect", "H4_fresh_confirmation_wins_a_local_effect",
                "H5_integrity_provenance_and_no_authority"))
    ck("verdict", rep["verdict"] == ("EXPERIMENT_SET_COMMITMENT_SUPPORTED" if core else "NOT_SUPPORTED"))
    ck("summary", all(rep["summary"][s][a][w] == {"declared": round(rate(s, a, w), 4),
                                                  "correct": round(rate(s, a, w, "correct"), 4)}
                      for s in sal for a in ARMS for w in WORLDS))
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("arm set", tuple(rep["design"]["arms"]) == ARMS)
    ck("design declared", (rep["design"]["designs"], rep["design"]["scan_rows"], rep["design"]["topup"],
                           rep["design"]["committed"], rep["design"]["commit_rows"])
       == (DESIGNS, SCAN_ROWS, TOPUP, COMMITTED, COMMIT_ROWS))

    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]

    total = 0
    for s in mem:
        for a, entries in mem[s].items():
            prev, bad = "", 0
            for e in entries:
                b = canon({k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                             "nonce", "created_at", "grants_authority", "executable")})
                ok = (e["prev"] == prev and e["tenant"] == TENANT
                      and sha(e["prev"].encode() + b + 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"]), b)
                    except Exception:
                        ok = False
                bad += 0 if ok else 1
                prev = e["hash"]
            total += len(entries)
            ck(f"memory chain {s}:{a}", bad == 0)
            ck(f"memory count {s}:{a}", len(entries) == len(WORLDS) * CAMPAIGNS)
            for wi, w in enumerate(WORLDS):
                base = wi * CAMPAIGNS
                ck(f"memory values {s}:{a}:{w}", all(
                    entries[base + i]["value"]["declared"] == sims[s][a][w][i]["declared"]
                    and entries[base + i]["value"]["selected"] == sims[s][a][w][i]["selected"]
                    and entries[base + i]["value"]["correct"] == sims[s][a][w][i]["correct"]
                    for i in range(CAMPAIGNS)))
    ck("memory total", total == len(WORLDS) * CAMPAIGNS * len(MEMORY_ARMS) * len(sal))
    ck("no engine source", not any(x.name.endswith(".py") and x.name != "verify_exs_offline.py"
                                   for x in d.rglob("*") if x.is_file()))

    print(f"{len(checks) - len(fails)}/{len(checks)} checks passed")
    for n in fails[:20]:
        print("FAIL", n)
    return 0 if not fails else 1


if __name__ == "__main__":
    raise SystemExit(main())
