#!/usr/bin/env python3
"""MAN standalone auditor — re-derives the trial-manifest 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

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", "manifest", "mixed50", "gated50", "gated25", "forged", "oracle")
MEMORY_ARMS = ARMS[:6]
FRAC = {"manifest": 1.00, "mixed50": 0.50, "gated50": 0.50, "gated25": 0.25}
GATED = {"gated50", "gated25", "manifest"}
TENANT, SEED = "cain42-man", "man"
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 manifested(salt, campaign, c, frac):
    return _u(salt, campaign, f"manifest|{c}") < frac


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)
    frac = FRAC.get(arm, 0.0)
    est, manifests, eligible = {}, [], []
    for c, t in w.items():
        has = bool(frac) and manifested(salt, campaign, c, frac)
        if arm == "oracle":
            est[c] = REAL_P if t["real"] else NULL_P
            eligible.append(c)
        elif arm == "forged":
            est[c] = 1.0 if t["successes"] else 0.0
            manifests.append({"candidate": c, "n": max(t["successes"], 1)})
            eligible.append(c)
        elif has:
            est[c] = t["successes"] / t["n"]
            manifests.append({"candidate": c, "n": t["n"]})
            eligible.append(c)
        elif arm in GATED:
            continue
        else:
            est[c] = t["successes"] / t["reported_trials"] if t["reported_trials"] else 0.0
            eligible.append(c)
    best = promote(est)
    declared = best is not None
    real = bool(best is not None and w[best]["real"])
    return {"arm": arm, "campaign": campaign, "estimates": {str(k): round(v, 6) for k, v in est.items()},
            "promoted": best, "declared": declared, "real": real,
            "false_promotion": bool(declared and not real), "correct": bool(declared and 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, "results": [{"candidate": c, "successes": t["successes"],
                                                 "reported_trials": t["reported_trials"], "n": t["n"],
                                                 "real": t["real"]} for c, t in sorted(w.items())],
            "manifested": len(manifests), "eligible": len(eligible)}


def main():
    if len(sys.argv) < 2:
        print("usage: verify_man_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", "MAN_MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
                                   "MAN_OMEGA_SEAL.json", "MAN_PUBKEY.pem", "MAN_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 / "MAN_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_manifest_restores_the_denominator", "H2_partial_compliance_does_not_degrade_gracefully",
        "H3_gating_helps_but_is_not_coverage", "H4_gating_costs_capability",
        "H5_a_forged_manifest_is_flagged", "H6_integrity_and_no_authority", "H7_external_review"})

    rep = json.loads((d / "MAN_RUN_REPORT.json").read_text())
    rows_file = json.loads((d / "MAN_ROWS.json").read_text())
    mem = json.loads((d / "MAN_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", "results", "manifested", "eligible"):
                    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

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

    H = rep["hypotheses"]
    ck("H1", all(rate(s, "manifest", "false_promotion") <= 0.05
                 and mean(s, "manifest", "mean_error") <= 0.5 * mean(s, "declared", "mean_error") for s in sal)
       and H["H1_manifest_restores_the_denominator"]["verdict"] == "SUPPORTED")
    ck("H2", all(rate(s, "mixed50", "false_promotion") > 0.08
                 and rate(s, "mixed50", "false_promotion")
                 >= rate(s, "manifest", "false_promotion") + 0.05 for s in sal)
       and H["H2_partial_compliance_does_not_degrade_gracefully"]["verdict"] == "SUPPORTED")
    h3_pred = all(rate(s, "gated50", "false_promotion")
                  <= rate(s, "mixed50", "false_promotion") - 0.03
                  and rate(s, "gated50", "false_promotion")
                  >= rate(s, "manifest", "false_promotion") + 0.01 for s in sal)
    ck("H3", h3_pred == (H["H3_gating_helps_but_is_not_coverage"]["verdict"] == "SUPPORTED"))
    ck("H4", all(rate(s, "gated50", "correct") <= rate(s, "manifest", "correct") - 0.05 for s in sal)
       and H["H4_gating_costs_capability"]["verdict"] == "SUPPORTED")
    ck("H5", all(rate(s, "forged", "false_promotion") > 0.40
                 and rep["hypotheses"]["H5_a_forged_manifest_is_flagged"]["detail"][s]["manifest_after_results"]
                 == rep["hypotheses"]["H5_a_forged_manifest_is_flagged"]["detail"][s]["campaigns_with_manifest"] > 0
                 for s in sal)
       and H["H5_a_forged_manifest_is_flagged"]["verdict"] == "SUPPORTED")
    h6 = H["H6_integrity_and_no_authority"]["detail"]
    ck("H6", all(h6[f"{s}:{a}"]["chain_and_signatures"] and h6[f"{s}:{a}"]["replay_refused"]
                 and h6[f"{s}:{a}"]["tamper_detected"] and h6[f"{s}:{a}"]["authority_from_memory_refused"]
                 and h6[f"{s}:{a}"]["authority_flag_false_everywhere"]
                 for s in sal for a in MEMORY_ARMS)
       and all(h6[f"{s}:provenance"]["manifest_without_result"] == 0
               and h6[f"{s}:provenance"]["honest_before"] == h6[f"{s}:provenance"]["honest_campaigns"] for s in sal)
       and H["H6_integrity_and_no_authority"]["verdict"] == "SUPPORTED")
    core = all(H[k]["verdict"] == "SUPPORTED" for k in
               ("H1_manifest_restores_the_denominator", "H2_partial_compliance_does_not_degrade_gracefully",
                "H3_gating_helps_but_is_not_coverage", "H4_gating_costs_capability",
                "H5_a_forged_manifest_is_flagged", "H6_integrity_and_no_authority"))
    ck("verdict", rep["verdict"] == ("TRIAL_MANIFEST_SUPPORTED" if core else "NOT_SUPPORTED"))
    ck("summary", all(rep["summary"][s][a] == {
        "false_promotion": round(rate(s, a, "false_promotion"), 4),
        "correct": round(rate(s, a, "correct"), 4), "declared": round(rate(s, a, "declared"), 4),
        "mean_error": round(mean(s, a, "mean_error"), 6),
        "mean_manifested": round(sum(r["manifested"] for r in sims[s][a]) / CAMPAIGNS, 3)}
        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]

    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)
            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 == "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 ("manifest", "mixed50", "gated50", "gated25"):
                if man_i:
                    ck(f"manifest before results {s}:{a}", all(man_i[k] < min(res[k]) for k in man_i))
                ck(f"honest manifests declare 24 {s}:{a}",
                   all(x["n"] == N_TRIALS for e in entries if e["kind"] == "manifest"
                       for x in e["value"]["manifests"]))
    ck("no engine source", not any(x.name.endswith(".py") and x.name != "verify_man_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())
