#!/usr/bin/env python3
"""RPL standalone auditor — re-derives every candidate, recipe and decision from the salts. No CAIN imports."""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

CANDS, NULLS, N, ROWS = 64, 32, 64, 256
P_NULL, P_REAL, BAR = 0.50, 0.65, 0.60
ARMS = ("TRUST", "REPEAT", "RECIPE", "AUDIT", "COMPLETE", "ORACLE")
TENANT, SEED = "cain42-rpl", "rpl"


def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def h(s): return hashlib.sha256(s.encode()).hexdigest()
def unit(salt, *p): return int(h("|".join((salt, *map(str, p))))[:8], 16) / float(1 << 32)
def truth_p(c): return P_NULL if c < NULLS else P_REAL
def is_real(c): return truth_p(c) >= BAR
def tie_of(salt, c): return 0 if unit(salt, "tie", c) < 0.5 else 1
def is_complete(salt, c): return unit(salt, "complete", c) < 0.5


def score(salt, c, tie):
    p = truth_p(c)
    rows = sorted(range(ROWS), key=lambda i: h(f"{salt}|{c}|{tie}|{i}"))[:N]
    return round(sum(1 for i in rows if unit(salt, "row", c, i) < p) / N, 6)


def recipe(salt, c):
    r = {"candidate": c, "n": N, "complete": is_complete(salt, c)}
    if r["complete"]:
        r["tie"] = tie_of(salt, c)
    return r


def decide(salt, c, arm):
    rec = recipe(salt, c)
    claimed = score(salt, c, tie_of(salt, c))
    verified = score(salt, c, rec.get("tie", 0))
    rep = abs(verified - claimed) < 1e-12
    d = {"candidate": c, "truth_p": truth_p(c), "real": is_real(c), "complete": rec["complete"],
         "tie": rec.get("tie"), "claimed": claimed, "verified": verified, "reproduced": rep,
         "promote": False, "reason": ""}
    if arm == "TRUST":
        d["promote"] = claimed >= BAR
        d["reason"] = "claim_clears_bar" if d["promote"] else "claim_below_bar"
    elif arm == "REPEAT":
        d["promote"] = claimed >= BAR
        d["reason"] = "self_repeat_clears_bar" if d["promote"] else "claim_below_bar"
    elif arm == "RECIPE":
        d["promote"] = claimed >= BAR and rep
        d["reason"] = "reproduced" if d["promote"] else ("score_not_reproduced" if claimed >= BAR else "claim_below_bar")
    elif arm == "AUDIT":
        if not rec["complete"]:
            d["reason"] = "incomplete_recipe_refused"
        else:
            d["promote"] = claimed >= BAR and rep
            d["reason"] = "reproduced" if d["promote"] else "claim_below_bar"
    elif arm == "COMPLETE":
        d["complete"] = True
        d["tie"] = tie_of(salt, c)
        d["verified"] = score(salt, c, d["tie"])
        d["reproduced"] = abs(d["verified"] - claimed) < 1e-12
        d["promote"] = claimed >= BAR and d["reproduced"]
        d["reason"] = "reproduced" if d["promote"] else "claim_below_bar"
    elif arm == "ORACLE":
        d["promote"] = is_real(c)
        d["reason"] = "truth"
    return d


def rate(xs): return round(sum(1 for x in xs if x) / len(xs), 6) if xs else 0.0


def nonce(agent, kind, key, value):
    return sha(canon({"agent": agent, "kind": kind, "key": key, "value": value}))[:16]


def pub_of(agent):
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
    k = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{agent}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


def verify_memory(entries, pubs):
    prev, bad = "", []
    for e in entries:
        e = {**e, "grants_authority": False, "executable": False}
        body = 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
        ok = ok and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"]
        ok = ok and e["nonce"] == nonce(e["agent"], e["kind"], e["key"], e["value"])
        if ok:
            try:
                Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(bytes.fromhex(e["sig"]), body)
            except Exception:
                ok = False
        if not ok:
            bad.append(e["seq"])
        prev = e["hash"]
    return bad


def merkle(files):
    l = sorted(sha(p.read_bytes()) for p in files)
    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)]
    return l[0] if l else sha(b"")


def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    ck, fail = [], []
    def check(n, ok, d=""):
        ck.append({"check": n, "ok": bool(ok), "detail": d})
        if not ok: fail.append(n)

    args = json.loads((root / "RPL_RUN_REPORT.json").read_text())
    rows = json.loads((root / "RPL_ROWS.json").read_text())
    mem = json.loads((root / "RPL_MEMORY.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    pre = json.loads((root / "RPL_PREREGISTRATION.json").read_text())
    man = json.loads((root / "MANIFEST.json").read_text())

    for k in ("salt1", "salt2"):
        check(f"salt commitment {k}", sha(salts[k].encode()) == pre["salts_commitment"][k])

    derived = {s: {a: [decide(salts[s], c, a) for c in range(CANDS)] for a in ARMS} for s in ("salt1", "salt2")}
    index = {(r["salt"], r["candidate"]): r for r in rows}
    mism = 0
    for s in derived:
        for c in range(CANDS):
            r = index.get((s, c))
            for a in ARMS:
                if r is None or any(r["arms"][a][k] != derived[s][a][c][k] for k in
                                    ("truth_p", "real", "complete", "tie", "claimed", "verified",
                                     "reproduced", "promote", "reason")):
                    mism += 1
    check("every candidate and every arm re-derives", mism == 0, f"{mism} mismatches")

    def fs(s, a): return rate([d["promote"] for d in derived[s][a] if not d["real"]])
    def ts(s, a): return rate([d["promote"] for d in derived[s][a] if d["real"]])
    def prom(s, a): return [d["candidate"] for d in derived[s][a] if d["promote"]]

    h1 = all(all(derived[s]["TRUST"][c]["promote"] == derived[s]["REPEAT"][c]["promote"] for c in range(CANDS)) for s in derived)
    h2 = True
    for s in derived:
        tr, rc = prom(s, "TRUST"), prom(s, "RECIPE")
        rej = [c for c in tr if c not in rc]
        h2 = h2 and bool(tr) and len(rej) / len(tr) >= 0.20 and all(not derived[s]["RECIPE"][c]["reproduced"] for c in rej)
    h3 = True
    for s in derived:
        ct = sum(1 for c in prom(s, "COMPLETE") if derived[s]["COMPLETE"][c]["real"])
        tt = sum(1 for c in prom(s, "TRUST") if derived[s]["TRUST"][c]["real"])
        h3 = h3 and tt > 0 and ct / tt >= 0.90 and all(derived[s]["COMPLETE"][c]["reproduced"] for c in prom(s, "COMPLETE"))
    h4 = True
    for s in derived:
        au, co = prom(s, "AUDIT"), prom(s, "COMPLETE")
        h4 = h4 and all(derived[s]["AUDIT"][c]["complete"] for c in au)
        h4 = h4 and all(derived[s]["AUDIT"][c]["reproduced"] for c in au)
        h4 = h4 and sum(1 for c in au if derived[s]["AUDIT"][c]["real"]) <= sum(1 for c in co if derived[s]["COMPLETE"][c]["real"])
    h5 = True
    for s in derived:
        h5 = h5 and fs(s, "COMPLETE") <= fs(s, "TRUST")
        h5 = h5 and all(derived[s][a][c]["reproduced"] for a in ("RECIPE", "AUDIT", "COMPLETE") for c in prom(s, a))
    computed = {"H1_self_repetition_is_a_no_op": "SUPPORTED" if h1 else "NOT_SUPPORTED",
                "H2_independent_rerun_rejects_unreproduced_promotions": "SUPPORTED" if h2 else "NOT_SUPPORTED",
                "H3_complete_record_restores_proof_at_no_cost": "SUPPORTED" if h3 else "NOT_SUPPORTED",
                "H4_refusing_an_incomplete_record_costs_power": "SUPPORTED" if h4 else "NOT_SUPPORTED",
                "H5_false_promotions_and_reproduction": "SUPPORTED" if h5 else "NOT_SUPPORTED"}
    mm = 0
    for s in derived:
        for a in ARMS:
            rep = args["measurements"][s][a]
            exp = {"false_promotion_rate": fs(s, a), "true_retention": ts(s, a),
                   "promotions": len(prom(s, a)),
                   "reproduced_promotions": sum(1 for c in prom(s, a) if derived[s][a][c]["reproduced"]),
                   "unreproduced_promotions": sum(1 for c in prom(s, a) if not derived[s][a][c]["reproduced"]),
                   "promotions_on_complete": sum(1 for c in prom(s, a) if derived[s][a][c]["complete"])}
            if any(rep.get(k) != v for k, v in exp.items()): mm += 1
    check("measurement summary re-derives", mm == 0, f"{mm} mismatches")
    check("H1-H5 recomputed (a NOT_SUPPORTED hypothesis is a valid result)", True, json.dumps(computed))

    pubs = {a: pub_of(a) for a in ("author", "analyst", "verifier")}
    check("published memory keys derive from the seed", pubs == mem["keys"])
    bad = []
    for key, es in mem["entries"].items():
        bad += [(key, b) for b in verify_memory(es, pubs)]
    check("every governed-memory entry verifies", not bad, str(bad[:5]))
    ok_probe = all(args["probes"][s]["chain_and_signatures"] and args["probes"][s]["replay_refused"]
                   and args["probes"][s]["tamper_detected"] and args["probes"][s]["recipes_before_results"]
                   and args["probes"][s]["authority_from_memory_refused"]
                   and args["probes"][s]["authority_flag_false_everywhere"] for s in ("salt1", "salt2"))
    for s in ("salt1", "salt2"):
        rs = [e["seq"] for e in mem["entries"][s] if e["kind"] == "recipe"]
        es = [e["seq"] for e in mem["entries"][s] if e["kind"] == "result"]
        check(f"{s} every recipe precedes every result", bool(rs) and bool(es) and max(rs) < min(es))
    check("H6 integrity, ordering and no authority", ok_probe)
    check("reported hypothesis verdicts match", {k: v.get("verdict") for k, v in args["hypotheses"].items()}
          == {**computed, "H6_integrity_and_recipe_ordering": "SUPPORTED" if ok_probe else "NOT_SUPPORTED",
              "H7_external_review": "BLOCKED"})
    check("verdict follows from H1-H6",
          args["verdict"] == ("REPRODUCTION_GATE_SUPPORTED" if (h1 and h2 and h3 and h4 and h5 and ok_probe) else "NOT_SUPPORTED"))

    fs_ = sorted(p for p in root.rglob("*") if p.is_file() and "__pycache__" not in p.parts
                 and p.name not in ("MANIFEST.json", "RPL_MANIFEST.json", "MERKLE_ROOT.txt",
                                    "RPL_SIGNED_BODY.json", "RPL_VERIFICATION_RESULTS.json",
                                    "RPL_TAMPER_RESULTS.json", "RPL_PUBLIC_CHECK.json",
                                    "PUBLICATION.json", "RPL_OMEGA_SEAL.json", "RPL_PUBKEY.pem"))
    body = {k: man[k] for k in ("schema", "evolution", "status", "name", "created_at", "verifier",
                                "pubkey_ed25519", "files", "merkle_root", "engine_withheld", "external_review")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
        check("manifest signature", True)
    except Exception:
        check("manifest signature", False)
    check("file hashes match the manifest", all(man["files"].get(str(p.relative_to(root))) == sha(p.read_bytes()) for p in fs_))
    check("manifest lists exactly the bundle files", sorted(man["files"]) == sorted(str(p.relative_to(root)) for p in fs_))
    check("merkle root recomputes", man["merkle_root"] == merkle(fs_))
    check("engine source withheld", man.get("engine_withheld") is True and not any(p.suffix == ".py" and "verify" not in p.name for p in fs_))
    check("no model calls", args.get("model_calls") == 0)
    check("status line", args.get("status") == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    check("external review not claimed", man.get("external_review") == "NOT_OBTAINED")

    print(json.dumps({"checks": len(ck), "passed": sum(1 for c in ck if c["ok"]), "failed": fail,
                      "verdict": args["verdict"]}, indent=1))
    return 0 if not fail else 1


if __name__ == "__main__":
    sys.exit(main())
