#!/usr/bin/env python3
"""IMB standalone auditor — re-derives the input-bound manifest study from the 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

CANDIDATES, N_REAL = 40, 12
N_TRIALS, FOCAL, FOCAL_REAL, FOCAL_NULL = 24, 8, 3, 5
REAL_P, NULL_P, OMIT, BAR = 0.72, 0.50, 0.60, 0.65
CAMPAIGNS = 200
ARMS = ("declared", "n_only", "bound", "forged", "bound_forged", "oracle")
MEMORY_ARMS = ARMS[:5]
TENANT, SEED = "cain42-imb", "imb"
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 _u(salt, campaign, tag):
    h = hashlib.sha256(f"{salt}|{campaign}|{tag}".encode()).digest()
    return int.from_bytes(h[:8], "big") / 2 ** 64


def roles(salt, campaign):
    order = sorted(range(CANDIDATES), key=lambda c: _u(salt, campaign, f"real|{c}"))
    real = set(order[:N_REAL])
    order2 = sorted(range(CANDIDATES), key=lambda c: _u(salt, campaign, f"focal|{c}"))
    fr = [c for c in order2 if c in real][:FOCAL_REAL]
    fn = [c for c in order2 if c not in real][:FOCAL_NULL]
    trials = {}
    for c in sorted(fr + fn):
        p = REAL_P if c in real else NULL_P
        s = rf = 0
        for t in range(N_TRIALS):
            if _u(salt, campaign, f"trial|{c}|{t}") < p:
                s += 1
            elif _u(salt, campaign, f"omit|{c}|{t}") >= OMIT:
                rf += 1
        trials[c] = {"real": c in real, "successes": s, "reported_trials": s + rf, "n": N_TRIALS}
    return trials


def promote(est):
    best = None
    for c, v in est.items():
        if v > BAR and (best is None or v > est[best] or (v == est[best] and c < best)):
            best = c
    return best


def run_campaign(salt, arm, campaign):
    w = roles(salt, campaign)
    est, manifests, detected, refused = {}, [], False, False
    for c, t in w.items():
        base = c * N_TRIALS
        executed = [base + i for i in range(N_TRIALS)]
        p = REAL_P if t["real"] else NULL_P
        ok_ids = [base + i for i in range(N_TRIALS) if _u(salt, campaign, f"trial|{c}|{i}") < p]
        if arm in ("forged", "bound_forged") and len(ok_ids) == N_TRIALS:
            ok_ids = ok_ids[:-1]
        if arm == "oracle":
            est[c] = p
        elif arm == "forged":
            manifests.append({"candidate": c, "n": max(len(ok_ids), 1), "inputs": ok_ids or [base]})
            est[c] = 1.0 if ok_ids else 0.0
        elif arm == "bound_forged":
            manifests.append({"candidate": c, "n": max(len(ok_ids), 1), "inputs": ok_ids or [base]})
            if sorted(ok_ids or [base]) != sorted(executed):
                detected = refused = True
                continue
            est[c] = t["successes"] / t["n"]
        elif arm == "bound":
            manifests.append({"candidate": c, "n": N_TRIALS, "inputs": executed})
            est[c] = t["successes"] / t["n"]
        elif arm == "n_only":
            manifests.append({"candidate": c, "n": N_TRIALS})
            est[c] = t["successes"] / t["n"]
        else:
            est[c] = t["successes"] / t["reported_trials"] if t["reported_trials"] else 0.0
    best = promote(est)
    return {"arm": arm, "campaign": campaign, "estimates": {str(k): round(v, 6) for k, v in est.items()},
            "promoted": best, "declared": best is not None,
            "real": bool(best is not None and w[best]["real"]),
            "false_promotion": bool(best is not None and not w[best]["real"]),
            "correct": bool(best is not None and w[best]["real"]),
            "mean_error": round(sum(abs(est[c] - (REAL_P if w[c]["real"] else NULL_P)) for c in est) / len(est), 6) if est else 0.0,
            "manifests": manifests, "detected": detected, "refused": refused,
            "manifested": len(manifests),
            "results": [{"candidate": c, "successes": t["successes"], "reported_trials": t["reported_trials"],
                         "n": t["n"], "real": t["real"],
                         "executed": [c * N_TRIALS + i for i in range(N_TRIALS)]}
                        for c, t in sorted(w.items())]}


def main():
    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", "IMB_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                                   "IMB_OMEGA_SEAL.json", "IMB_PUBKEY.pem", "IMB_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 / "IMB_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_the_forgery_works_without_binding", "H2_binding_accepts_honest_manifests",
        "H3_binding_detects_and_refuses_the_forgery", "H4_binding_costs_no_capability",
        "H5_integrity_and_no_authority", "H6_external_review"})

    rep = json.loads((d / "IMB_RUN_REPORT.json").read_text())
    rows_file = json.loads((d / "IMB_ROWS.json").read_text())
    mem = json.loads((d / "IMB_MEMORY.json").read_text())

    sims = {s: {a: [run_campaign(sal[s], a, i) for i in range(CAMPAIGNS)] for a in ARMS} for s in sal}
    for s in sal:
        for a in ARMS:
            got, sim = rows_file[s][a], sims[s][a]
            ck(f"rows {s}:{a}", len(got) == len(sim))
            bad = 0
            for g, r in zip(got, sim):
                for key in ("promoted", "declared", "real", "false_promotion", "correct", "mean_error",
                            "estimates", "manifests", "detected", "refused", "manifested", "results"):
                    if g.get(key) != r.get(key):
                        bad += 1
                        break
            ck(f"values {s}:{a}", bad == 0)

    def rate(s, a, key):
        return sum(1 for r in sims[s][a] if r[key]) / CAMPAIGNS

    H = rep["hypotheses"]
    ck("H1", all(rate(s, "forged", "false_promotion") > 0.40 for s in sal)
       and H["H1_the_forgery_works_without_binding"]["verdict"] == "SUPPORTED")
    ck("H2", all(rate(s, "bound", "false_promotion") <= 0.05
                 and sum(1 for r in sims[s]["bound"] if r["detected"] or r["refused"]) == 0 for s in sal)
       and H["H2_binding_accepts_honest_manifests"]["verdict"] == "SUPPORTED")
    ck("H3", all(all(r["detected"] and r["refused"] and not r["declared"]
                     for r in sims[s]["bound_forged"]) for s in sal)
       and H["H3_binding_detects_and_refuses_the_forgery"]["verdict"] == "SUPPORTED")
    ck("H4", all(rate(s, "bound", "correct") >= rate(s, "n_only", "correct") - 0.01 for s in sal)
       and H["H4_binding_costs_no_capability"]["verdict"] == "SUPPORTED")
    h5 = H["H5_integrity_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"]["manifest_without_result"] == 0
               and h5[f"{s}:provenance"]["honest_before"] == h5[f"{s}:provenance"]["honest_campaigns"] for s in sal)
       and H["H5_integrity_and_no_authority"]["verdict"] == "SUPPORTED")
    core = all(H[k]["verdict"] == "SUPPORTED" for k in
               ("H1_the_forgery_works_without_binding", "H2_binding_accepts_honest_manifests",
                "H3_binding_detects_and_refuses_the_forgery", "H4_binding_costs_no_capability",
                "H5_integrity_and_no_authority"))
    ck("verdict", rep["verdict"] == ("INPUT_MANIFEST_SUPPORTED" if core else "NOT_SUPPORTED"))
    ck("summary", all(rep["summary"][s][a]["false_promotion"] == round(rate(s, a, "false_promotion"), 4)
                      and rep["summary"][s][a]["correct"] == round(rate(s, a, "correct"), 4)
                      for s in sal for a in ARMS))
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("arm set", tuple(rep["design"]["arms"]) == ARMS)

    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]

    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"]
            ck(f"memory chain {s}:{a}", bad == 0)
            man_i = {e["key"]: e["seq"] for e in entries if e["kind"] == "manifest"}
            res = {}
            for e in entries:
                if e["kind"] == "result":
                    res.setdefault(e["key"], []).append(e["seq"])
            if a in ("forged", "bound_forged"):
                ck(f"forged manifest after results {s}:{a}", man_i and all(man_i[k] > max(res[k]) for k in man_i))
            elif a in ("n_only", "bound"):
                ck(f"manifest before results {s}:{a}", man_i and all(man_i[k] < min(res[k]) for k in man_i))
    ck("no engine source", not any(x.name.endswith(".py") and x.name != "verify_imb_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())
