#!/usr/bin/env python3
"""EBL standalone auditor — re-derives the whole budget-ledger study from the revealed salts.

Rebuilds the four families, the six arms, every transfer, every attempt, every solvency verdict and
every task outcome; recomputes all hypotheses and the verdict; then verifies the signed manifest,
file hashes and Merkle root, the salt commitments, and every Ed25519 signature and SHA-256 link of
the exported governed memory. Imports no CAIN code.

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

import hashlib
import json
import sys
from pathlib import Path

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

FAMILIES = ("F0", "F1", "F2", "F3")
AGENTS = ("A0", "A1", "A2", "A3")
OWNER = {"A0": "F0", "A1": "F1", "A2": "F2", "A3": "F3"}
COST = {"F0": 1, "F1": 1, "F2": 4, "F3": 4}
TASKS, GENS, ENDOW, WORLDS = 30, 4, 50, 12
P_BASE = {"F0": 0.90, "F1": 0.85, "F2": 0.80, "F3": 0.75}
JITTER = 0.06
ARMS = ("STATIC", "HALF", "LEDGER", "AUDIT", "TRUST", "POOL")
MEMORY_ARMS = ("LEDGER", "AUDIT", "TRUST")
TENANT, SEED = "cain42-ebl", "ebl"


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, *parts):
    return int(h("|".join((salt, *map(str, parts))))[:8], 16) / float(1 << 32)


def success_p(salt, world, fam):
    return round(P_BASE[fam] + (unit(salt, "p", world, fam) - 0.5) * JITTER, 6)


def task_success(salt, world, fam, gen, i, p):
    return unit(salt, "task", world, fam, gen, i) < p


def need_units(fam):
    return TASKS * COST[fam]


def true_surplus(agent):
    return max(0, ENDOW - need_units(OWNER[agent]))


def deficit(fam):
    return max(0, need_units(fam) - ENDOW)


def offers_for(arm):
    if arm in ("STATIC", "POOL"):
        return {}
    true = {a: true_surplus(a) for a in AGENTS}
    if arm == "HALF":
        return {a: v // 2 for a, v in true.items()}
    if arm == "TRUST":
        return {a: (40 if a == "A0" else v) for a, v in true.items()}
    if arm == "AUDIT":
        return {a: min(40 if a == "A0" else v, true[a]) for a, v in true.items()}
    return true


def transfers(arm):
    offers = {a: v for a, v in offers_for(arm).items() if v > 0}
    recv = [f for f in FAMILIES if deficit(f) > 0]
    if not offers or not recv:
        return [], offers, {}
    total = sum(offers.values())
    share = total // len(recv)
    remainder = total - share * len(recv)
    want = {f: share + (1 if i < remainder else 0) for i, f in enumerate(recv)}
    out, sent, left = [], {a: 0 for a in offers}, dict(offers)
    for f in recv:
        need = want[f]
        for a in AGENTS:
            if need <= 0:
                break
            if a not in left:
                continue
            give = min(left[a], need)
            if give <= 0:
                continue
            out.append({"from": a, "to_family": f, "units": give})
            left[a] -= give
            sent[a] += give
            need -= give
    return out, offers, sent


def pool_attempts():
    budget = len(AGENTS) * ENDOW
    attempts = {}
    for f in ("F0", "F1"):
        n = min(TASKS, budget // COST[f])
        attempts[f] = n
        budget -= n * COST[f]
    hard = [f for f in FAMILIES if f not in attempts]
    share = budget // len(hard)
    for i, f in enumerate(hard):
        b = share + (budget - share * len(hard) if i == 0 else 0)
        attempts[f] = min(TASKS, b // COST[f])
    return attempts


def run_gen(salt, world, arm, gen):
    p = {f: success_p(salt, world, f) for f in FAMILIES}
    xf, offers, sent = transfers(arm) if arm not in ("STATIC", "POOL") else ([], {}, {})
    received = {f: 0 for f in FAMILIES}
    for t in xf:
        received[t["to_family"]] += t["units"]
    if arm == "POOL":
        attempts = pool_attempts()
    elif arm == "TRUST":
        attempts = {}
        for a in AGENTS:
            f = OWNER[a]
            avail = ENDOW + received[f]
            attempts[f] = min(TASKS, max(0, avail // COST[f]))
    else:
        attempts = {}
        for a in AGENTS:
            f = OWNER[a]
            avail = ENDOW - sent.get(a, 0) + received[f]
            attempts[f] = min(TASKS, max(0, avail // COST[f]))
    spend = {f: attempts[f] * COST[f] for f in FAMILIES}
    solved = 0
    successes = {}
    for f in FAMILIES:
        row = [task_success(salt, world, f, gen, i, p[f]) for i in range(attempts[f])]
        successes[f] = row
        solved += sum(1 for ok in row if ok)
    overdraft = {}
    for a in AGENTS:
        outflow = spend[OWNER[a]] + sent.get(a, 0)
        inflow = received[OWNER[a]]
        overdraft[a] = max(0, outflow - ENDOW - inflow) if arm == "TRUST" else 0
    unbacked_units = {f: 0.0 for f in FAMILIES}
    for t in xf:
        a = t["from"]
        if sent.get(a, 0) > 0 and overdraft.get(a, 0) > 0:
            unbacked_units[t["to_family"]] += t["units"] * overdraft[a] / sent[a]
    unbacked_attempts = {}
    backed_attempts = {}
    backed = solved
    for f in FAMILIES:
        if arm == "POOL":
            unbacked_attempts[f] = 0
            backed_attempts[f] = attempts[f]
            continue
        recv_backed = received[f] - unbacked_units[f]
        cap = int((ENDOW + recv_backed) // COST[f])
        ba = min(attempts[f], max(0, cap))
        k = attempts[f] - ba
        unbacked_attempts[f] = k
        backed_attempts[f] = ba
        if k:
            backed -= sum(1 for ok in successes[f][attempts[f] - k:] if ok)
    unused = {a: ENDOW - spend[OWNER[a]] - sent.get(a, 0) + received[OWNER[a]] for a in AGENTS}
    total_spend = sum(spend.values())
    conservation = total_spend + sum(unused.values()) == len(AGENTS) * ENDOW
    return {"gen": gen, "transfers": xf, "attempts": attempts, "spend": spend, "solved": solved,
            "backed_solved": backed, "unbacked_attempts": unbacked_attempts, "overdraft": overdraft,
            "unused": unused, "total_spend": total_spend, "conservation": conservation, "p": p}


def run_world(salt, world, arm):
    gens = [run_gen(salt, world, arm, g) for g in range(GENS)]
    return {"solved": sum(g["solved"] for g in gens),
            "backed_solved": sum(g["backed_solved"] for g in gens),
            "attempts": sum(sum(g["attempts"].values()) for g in gens),
            "spend": sum(g["total_spend"] for g in gens),
            "unused": sum(sum(g["unused"].values()) for g in gens),
            "overdraft": sum(sum(g["overdraft"].values()) for g in gens),
            "unbacked_attempts": sum(sum(g["unbacked_attempts"].values()) for g in gens),
            "conservation": all(g["conservation"] for g in gens)}


def mean(xs):
    return round(sum(xs) / len(xs), 4) 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(name, ok, detail=""):
        ck.append({"check": name, "ok": bool(ok), "detail": detail})
        if not ok:
            fail.append(name)

    args = json.loads((root / "EBL_RUN_REPORT.json").read_text())
    rows = json.loads((root / "EBL_ROWS.json").read_text())
    mem = json.loads((root / "EBL_MEMORY.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    pre = json.loads((root / "EBL_PREREGISTRATION.json").read_text())
    man = json.loads((root / "MANIFEST.json").read_text())

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

    # re-derive every world
    derived = {s: {a: [run_world(salts[s], w, a) for w in range(WORLDS)] for a in ARMS}
               for s in ("salt1", "salt2")}
    mismatch = 0
    index = {(r["salt"], r["arm"], r["world"]): r for r in rows}
    for s in derived:
        for a in ARMS:
            for w, got in enumerate(derived[s][a]):
                r = index.get((s, a, w))
                if r is None or any(r[k] != got[k] for k in ("solved", "backed_solved", "attempts",
                                                             "spend", "unused", "overdraft",
                                                             "unbacked_attempts", "conservation")):
                    mismatch += 1
    check("every one of the 144 arm-world rows re-derives exactly", mismatch == 0, f"{mismatch} mismatches")

    # aggregates
    mismatch = 0
    for s in derived:
        for a in ARMS:
            m = args["measurements"][s][a]
            if m["solved"] != mean([x["solved"] for x in derived[s][a]]):
                mismatch += 1
            if m["attempts"] != mean([x["attempts"] for x in derived[s][a]]):
                mismatch += 1
            if m["overdraft"] != mean([x["overdraft"] for x in derived[s][a]]):
                mismatch += 1
    check("aggregates and hypotheses re-derive", mismatch == 0, f"{mismatch} mismatches")

    # hypotheses and verdict, recomputed
    def solved(s, a):
        return mean([x["solved"] for x in derived[s][a]])

    h1 = all(solved(s, "LEDGER") - solved(s, "STATIC") >= 20 for s in derived)
    h2 = all(abs(solved(s, "LEDGER") - solved(s, "POOL")) <= 4 for s in derived)
    h3 = all(solved(s, "LEDGER") - solved(s, "HALF") >= 6 for s in derived)
    h4 = True
    for s in derived:
        over = sum(x["overdraft"] for x in derived[s]["TRUST"])
        unb = sum(x["unbacked_attempts"] for x in derived[s]["TRUST"])
        backed = mean([x["backed_solved"] for x in derived[s]["TRUST"]])
        clean = all(x["conservation"] for a in ("STATIC", "HALF", "LEDGER", "AUDIT", "POOL", "TRUST")
                    for x in derived[s][a])
        no_over = all(x["overdraft"] == 0 for a in ("STATIC", "HALF", "LEDGER", "AUDIT", "POOL")
                      for x in derived[s][a])
        h4 = h4 and over > 0 and unb > 0 and backed <= solved(s, "LEDGER") + 2 and clean and no_over
        h4 = h4 and solved(s, "AUDIT") == solved(s, "LEDGER")
    check("H1 ledger beats static", h1)
    check("H2 ledger matches pool", h2)
    check("H3 full surplus beats half", h3)
    check("H4 solvency is a ledger property", h4)
    reported = {k: v.get("verdict") for k, v in args["hypotheses"].items()}
    expected = {"H1_ledger_beats_static": "SUPPORTED" if h1 else "NOT_SUPPORTED",
                "H2_ledger_matches_pool": "SUPPORTED" if h2 else "NOT_SUPPORTED",
                "H3_full_surplus_beats_half": "SUPPORTED" if h3 else "NOT_SUPPORTED",
                "H4_solvency_is_a_ledger_property": "SUPPORTED" if h4 else "NOT_SUPPORTED",
                "H5_integrity_and_no_authority": reported.get("H5_integrity_and_no_authority"),
                "H6_external_review": "BLOCKED"}
    check("reported hypothesis verdicts match the re-derivation", reported == expected,
          json.dumps({"reported": reported, "expected": expected}))

    # memory
    pubs = {a: pub_of(a) for a in AGENTS}
    check("published memory keys derive from the seed", pubs == mem["keys"])
    bad_any, entry_count = [], 0
    for key, entries in mem["entries"].items():
        entry_count += len(entries)
        bad = verify_memory(entries, pubs)
        bad_any += [(key, b) for b in bad]
    check("every governed-memory entry verifies (signature and chain)", not bad_any, str(bad_any[:5]))
    check("authority flags false on every entry",
          all(e["grants_authority"] is False and e["executable"] is False
              for es in mem["entries"].values() for e in es))
    # the memory's own record of every attempt and transfer must agree with the measured rows
    mem_mismatch = 0
    for key, entries in mem["entries"].items():
        salt, arm = key.split(":", 1)
        for e in entries:
            v = e["value"]
            row = index.get((salt, arm, v["world"]))
            if row is None:
                mem_mismatch += 1
                continue
            gen = row["gens"][v["gen"]]
            if e["kind"] == "attempt":
                f = v["family"]
                if gen["attempts"][f] != v["attempts"] or gen["spend"][f] != v["spend"]:
                    mem_mismatch += 1
            elif e["kind"] == "transfer":
                if not any(t["from"] == v["from"] and t["to_family"] == v["to_family"]
                           and t["units"] == v["units"] for t in gen["transfers"]):
                    mem_mismatch += 1
    check("memory records agree with the measured rows", mem_mismatch == 0, f"{mem_mismatch} mismatches")

    # probes
    ok_probe = True
    for k, p in args["probes"].items():
        ok_probe = ok_probe and p["chain_and_signatures"] and p["replay_refused"] and p["tamper_detected"] \
                   and p["authority_from_memory_refused"] and p["authority_flag_false_everywhere"]
    check("H5 integrity and no-authority probes", ok_probe)
    check("verdict follows from H1-H5",
          args["verdict"] == ("EXPERIMENT_BUDGET_LEDGER_SUPPORTED" if (h1 and h2 and h3 and h4 and ok_probe)
                              else "NOT_SUPPORTED"))

    # manifest
    fs = sorted(p for p in root.rglob("*") if p.is_file()
                and p.name not in (".DS_Store",) and "__pycache__" not in p.parts
                and p.name not in ("MANIFEST.json", "EBL_MANIFEST.json", "MERKLE_ROOT.txt",
                                   "EBL_SIGNED_BODY.json", "EBL_VERIFICATION_RESULTS.json",
                                   "EBL_TAMPER_RESULTS.json", "EBL_PUBLIC_CHECK.json", "PUBLICATION.json",
                                   "EBL_OMEGA_SEAL.json", "EBL_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,
                      "memory_entries": entry_count,
                      "verdict": args["verdict"]}, indent=1))
    return 0 if not fail else 1


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