#!/usr/bin/env python3
"""RFL standalone auditor — re-derives the retrieval-flood study from the revealed salts. No CAIN imports."""
from __future__ import annotations

import hashlib, json, sys
from pathlib import Path

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

FAMILIES = 40
HONEST_WRITERS = 3
ADV_KEYS = 10
ADV_ROOT = 9
FLOOD_MIN, FLOOD_MAX = 8, 12
K = 5
AUDIT_CAP = 20
WORLDS = 12
ARMS = ("RECENCY", "CLAIMED", "VERIFIED", "QUOTA_WRITER", "QUOTA_ROOT", "AUDIT", "ORACLE")
MEMORY_ARMS = ARMS[:-1]
TENANT, SEED = "cain42-rfl", "rfl"
SIGNERS = ("agent0", "agent1", "agent2", "adversary", "verifier")
CHECKS = []


def ok(n, c):
    CHECKS.append((n, bool(c))); return bool(c)


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, tag): return int.from_bytes(hashlib.sha256(f"{salt}|{tag}".encode()).digest()[:8], "big")


def build(salt):
    entries = []; order = 0
    for f in range(FAMILIES):
        entries.append({"id": f"t{f}", "fam": f, "writer": f % HONEST_WRITERS, "root": f % HONEST_WRITERS,
                        "claim": 0.90, "verified": True, "true_success": 0.90, "order": order}); order += 1
    for f in range(FAMILIES):
        depth = FLOOD_MIN + u(salt, f"depth|{f}") % (FLOOD_MAX - FLOOD_MIN + 1)
        for k in range(depth):
            key = u(salt, f"key|{f}|{k}") % ADV_KEYS
            entries.append({"id": f"a{f}-{k}", "fam": f, "writer": ADV_KEYS + key, "root": ADV_ROOT,
                            "claim": 1.0, "verified": False, "true_success": 0.10, "order": order}); order += 1
    entries.sort(key=lambda e: (e["verified"], e["order"]))
    return entries


def ranked(entries, fam, policy):
    pool = [e for e in entries if e["fam"] == fam]
    if policy == "RECENCY": return sorted(pool, key=lambda e: -e["order"])
    if policy in ("CLAIMED", "QUOTA_WRITER", "QUOTA_ROOT", "AUDIT"):
        r = sorted(pool, key=lambda e: (-e["claim"], -e["order"]))
        if policy in ("QUOTA_WRITER", "QUOTA_ROOT"):
            cap = {}; out = []
            for e in r:
                key = e["writer"] if policy == "QUOTA_WRITER" else e["root"]
                if cap.get(key, 0) < 2:
                    out.append(e); cap[key] = cap.get(key, 0) + 1
            return out
        return r
    if policy == "VERIFIED":
        return sorted([e for e in pool if e["verified"]], key=lambda e: (-e["claim"], -e["order"]))
    return sorted([e for e in pool if e["verified"]], key=lambda e: e["fam"])


def run_world(salt):
    entries = build(salt); out = {}
    for arm in ARMS:
        okn = audits = false_exec = 0
        for f in range(FAMILIES):
            r = ranked(entries, f, arm)
            if arm == "AUDIT":
                hit = None
                for e in r[:AUDIT_CAP]:
                    audits += 1
                    if e["verified"]: hit = e; break
                if hit: okn += 1
                else: false_exec += 1
                continue
            top = r[:K]
            if any(e["verified"] for e in top): okn += 1
            else: false_exec += 1
        out[arm] = {"success": round(okn / FAMILIES, 6), "audits_per_query": round(audits / FAMILIES, 6),
                    "false_exec": round(false_exec / FAMILIES, 6)}
    out["_verified_true"] = sum(1 for e in entries if e["verified"] and e["true_success"] >= 0.5)
    out["_verified_false"] = sum(1 for e in entries if e["verified"] and e["true_success"] < 0.5)
    out["_false_total"] = sum(1 for e in entries if not e["verified"])
    return {"arms": out, "entries": entries}


def mean(xs): return round(sum(xs) / len(xs), 6)
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 / "RFL_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())
    salts = json.loads((d / "SALTS.json").read_text()); report = json.loads((d / "RFL_RUN_REPORT.json").read_text())
    worlds_pub = json.loads((d / "RFL_WORLDS.json").read_text()); memory = json.loads((d / "RFL_MEMORY.json").read_text())
    for k, v in salts.items(): ok(f"salt commitment {k}", report["salts"][k] == sha(v.encode()))
    derived = {}
    for label in ("salt1", "salt2"):
        ws = [run_world(sha(f"{salts[label]}|world|{w}".encode())) for w in range(WORLDS)]
        summary = {}
        for a in ARMS:
            summary[a] = {"success": mean([w["arms"][a]["success"] for w in ws]),
                          "audits_per_query": mean([w["arms"][a]["audits_per_query"] for w in ws]),
                          "false_exec": mean([w["arms"][a]["false_exec"] for w in ws])}
            for f in ("success", "audits_per_query", "false_exec"):
                ok(f"{label} {a} {f}", abs(report["measures"][label][a][f] - summary[a][f]) < 1e-9)
            for w in range(WORLDS):
                for f in ("success", "audits_per_query", "false_exec"):
                    ok(f"{label} {a} w{w} {f}", abs(worlds_pub[label][a][w][f] - ws[w]["arms"][a][f]) < 1e-9)
        summary["_verified_true"] = ws[0]["arms"]["_verified_true"]
        summary["_verified_false"] = ws[0]["arms"]["_verified_false"]
        summary["_false_total"] = ws[0]["arms"]["_false_total"]
        derived[label] = summary
        for a in MEMORY_ARMS:
            verify_memory(memory[label][a], f"{label}:{a}")
            ok(f"{label} {a} entries", len(memory[label][a]) == report["memory"][label][a]["entries"])
            pubs = {}
            for e in memory[label][a]:
                if e["kind"] == "retrieval":
                    pubs[e["value"]["world"]] = e["value"]
            good = True
            for w in range(WORLDS):
                dd = ws[w]["arms"][a]; v = pubs.get(w)
                good = good and v is not None and abs(v["results"][a]["success"] - dd["success"]) < 1e-9 \
                    and abs(v["results"][a]["audits"] - dd["audits_per_query"]) < 1e-9 \
                    and abs(v["results"][a]["false_exec"] - dd["false_exec"]) < 1e-9
            ok(f"{label} {a} retrieval batches", good)
    S = derived; H = report["hypotheses"]
    computed = {
        "H1_claim_ranking_is_captured": all(S[s]["RECENCY"]["success"] == 0.0 and S[s]["CLAIMED"]["success"] == 0.0 and
                                            S[s]["RECENCY"]["false_exec"] == 1.0 and S[s]["CLAIMED"]["false_exec"] == 1.0 for s in S),
        "H2_admission_verification_is_free_at_retrieval": all(
            S[s]["VERIFIED"]["success"] == 1.0 and S[s]["VERIFIED"]["audits_per_query"] == 0.0 and
            S[s]["VERIFIED"]["false_exec"] == 0.0 for s in S),
        "H3_quota_must_be_per_root": all(S[s]["QUOTA_WRITER"]["success"] == 0.0 and S[s]["QUOTA_ROOT"]["success"] == 1.0 for s in S),
        "H4_post_retrieval_audit_has_a_flood_tax": all(
            S[s]["AUDIT"]["success"] == 1.0 and S[s]["AUDIT"]["audits_per_query"] >= 8.0 for s in S),
        "H5_integrity_and_admission": all(S[s]["_verified_true"] == 40 and S[s]["_verified_false"] == 0 and
                                          S[s]["_false_total"] >= 320 for s in S),
    }
    for k, v in computed.items():
        ok(f"{k} ok", H[k]["ok"] == v)
        ok(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if v else "NOT_SUPPORTED"))
    ok("H6 blocked", H["H6_external_review"]["verdict"] == "BLOCKED")
    core = all(H[k]["ok"] for k in H if k != "H6_external_review")
    ok("verdict", report["verdict"] == ("RETRIEVAL_FLOOD_SUPPORTED" if core else "NOT_SUPPORTED"))
    passed = sum(1 for _, g in CHECKS if g)
    for n, g in CHECKS:
        if not g: print("FAIL", n)
    print(f"{passed}/{len(CHECKS)} checks passed")
    return 0 if passed == len(CHECKS) else 1


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