#!/usr/bin/env python3
"""HDO standalone auditor. Imports no CAIN code; runs from a clean copy of the bundle.

Verifies the manifest, every file, the salt commitment, every signed stage record in the governed
memory, and **re-derives the whole campaign from the revealed salts**: the 16 permutations, the 24
two-stage tasks, all ten handoff policies, every per-world solved/cost row, the forged-handoff
accounting, the replay, and every hypothesis.

Usage: python3 verify_hdo_offline.py [bundle_dir]
"""
from __future__ import annotations

import hashlib
import json
import random
import statistics
import sys
from pathlib import Path

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

N = 16
M = 64
TASKS = 24
BUDGET = 72
P_S1_A = 0.95
P_S1_B = 0.55
P_S2 = 0.95
ARMS = ["exact", "no_handoff", "hash", "summary8", "churn_exact", "churn_no_handoff",
        "poison_trust", "poison_verified", "stage1_only", "stage2_only"]
WORLDS = 48
TENANT = "cain42-hdo"
SEED = "hdo"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
AGENT_NAMES = ["atlas", "borealis", "cetus", "draco", "mallory"]


def sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def canon(o) -> bytes:
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def mean(xs):
    return statistics.mean(xs) if xs else 0.0


def perms(salt, world):
    out = []
    for i in range(N):
        r = random.Random(int(sha(canon([salt, world, "perm", i]))[:16], 16))
        p = list(range(M))
        r.shuffle(p)
        out.append(p)
    return out


def comp(p, q):
    return [p[q[x]] for x in range(M)]


def build(salt, world):
    ps = perms(salt, world)
    r = random.Random(int(sha(canon([salt, world, "tasks"]))[:16], 16))
    tasks = []
    seen = set()
    while len(tasks) < TASKS:
        a, b, c, d = r.sample(range(N), 4)
        if (a, b, c, d) in seen:
            continue
        seen.add((a, b, c, d))
        s1 = comp(ps[a], ps[b])
        s2 = comp(ps[c], ps[d])
        final = comp(s1, s2)
        rr = random.Random(int(sha(canon([salt, world, "draws", a, b, c, d]))[:16], 16))
        tasks.append({"a": a, "b": b, "c": c, "d": d, "s1": s1, "s2": s2, "final": final,
                      "s1_a": 1 if rr.random() < P_S1_A else 0,
                      "s1_b": 1 if rr.random() < P_S1_B else 0,
                      "s2": 1 if rr.random() < P_S2 else 0})
    return {"ps": ps, "tasks": tasks}


def handoff_hash(s1):
    return sha(canon(list(s1)))


def run_arm(arm, d):
    solved = 0
    cost = 0
    false_records = 0
    false_accepted = 0
    for t in d["tasks"]:
        if arm in ("exact", "churn_exact"):
            cost += 2
            solved += t["s1_a"] & t["s2"]
        elif arm in ("no_handoff", "hash", "churn_no_handoff"):
            cost += 3
            solved += t["s1_b"] & t["s2"]
        elif arm == "summary8":
            cost += 2
            solved += 0
        elif arm == "poison_trust":
            cost += 2
            false_records += 1
            false_accepted += 1
            solved += 0
        elif arm == "poison_verified":
            cost += 3
            false_records += 1
            solved += t["s1_b"] & t["s2"]
        elif arm == "stage1_only":
            cost += 1
            solved += 0
        elif arm == "stage2_only":
            cost += 1
            solved += 0
        else:
            raise ValueError(arm)
    return {"solved": solved, "cost": cost, "false_records": false_records,
            "false_accepted": false_accepted}


def replay_exact(records, d):
    stage1 = {(r["value"]["a"], r["value"]["b"], r["value"]["c"], r["value"]["d"]): r for r in records if r["kind"] == "stage1"}
    stage2 = {(r["value"]["a"], r["value"]["b"], r["value"]["c"], r["value"]["d"]): r for r in records if r["kind"] == "stage2"}
    ok = True
    solved = 0
    for t in d["tasks"]:
        r1 = stage1.get((t["a"], t["b"], t["c"], t["d"]))
        r2 = stage2.get((t["a"], t["b"], t["c"], t["d"]))
        if r1 is None or r1["value"]["s1"] != t["s1"] or r1["value"]["s1_hash"] != handoff_hash(t["s1"]):
            ok = False
            continue
        if r2 is None or r2["value"]["final_hash"] != sha(canon(t["final"])):
            ok = False
        solved += r1["value"]["success"] & t["s2"]
        if r1["value"]["success"] != t["s1_a"]:
            ok = False
    return ok, solved


def pubhex(agent):
    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_entries(entries, pubs):
    prev = ""
    bad = []
    for e in entries:
        payload = {k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev",
                                     "created_at", "grants_authority", "executable")}
        body = canon(payload)
        ok = (e["prev"] == prev and e["tenant"] == TENANT
              and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"])
        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"")


class Checker:
    def __init__(self):
        self.n = 0
        self.bad = []

    def ok(self, cond, name, detail=""):
        self.n += 1
        if not cond:
            self.bad.append(f"{name}: {detail}")

    def eq(self, a, b, name):
        self.ok(a == b, name, f"{a!r} != {b!r}")

    def close(self, a, b, name):
        self.ok(abs(a - b) < 1e-9, name, f"{a!r} != {b!r}")


def verify(root: Path):
    c = Checker()
    man = json.loads((root / "HDO_MANIFEST.json").read_text())
    c.eq(man["schema"], "cain42.hdo.manifest.v1", "manifest schema")
    c.eq(man["evolution"], "HDO", "evolution")
    c.eq(man["status"], STATUS, "status line")
    for name, h in man["files"].items():
        p = root / name
        c.ok(p.exists(), f"file present {name}")
        if p.exists():
            c.eq(sha(p.read_bytes()), h, f"file hash {name}")
    c.eq(merkle([root / n for n in man["files"]]), man["merkle_root"], "merkle root")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon({k: man[k] for k in man if k != "signature"}))
        sig_ok = True
    except Exception:
        sig_ok = False
    c.ok(sig_ok, "manifest signature")
    rep = json.loads((root / "HDO_RUN_REPORT.json").read_text())
    salts = json.loads((root / "SALTS.json").read_text())
    frz = json.loads((root / "HDO_PREREGISTRATION_FREEZE.json").read_text())
    pre = json.loads((root / "HDO_PREREGISTRATION.json").read_text())
    c.eq(frz["preregistration_sha256"], sha((root / "HDO_PREREGISTRATION.json").read_bytes()),
         "prereg hash")
    c.eq({k: sha(v.encode()) for k, v in salts.items()}, frz["salt_commitments"], "salt commitment")
    c.eq(pre["salts_commitment"], frz["salt_commitments"], "prereg salt commitment")

    pubs = {a: pubhex(a) for a in AGENT_NAMES}
    res = {}
    for name in ("salt1", "salt2"):
        salt = salts[name]
        cell = rep["scenarios"][name]
        ds = [build(salt, w) for w in range(WORLDS)]
        for arm in ARMS:
            runs = [run_arm(arm, d) for d in ds]
            got = {
                "solved": [r["solved"] for r in runs],
                "cost": [r["cost"] for r in runs],
                "solved_mean": mean([r["solved"] for r in runs]),
                "cost_mean": mean([r["cost"] for r in runs]),
                "cost_per_solve": mean([r["cost"] for r in runs])
                / max(1e-9, mean([r["solved"] for r in runs])),
                "false_records": runs[0]["false_records"],
                "false_accepted": runs[0]["false_accepted"],
            }
            for k in ("solved", "cost", "false_records", "false_accepted"):
                c.eq(got[k], cell["arms"][arm][k], f"{name} {arm} {k}")
            for k in ("solved_mean", "cost_mean", "cost_per_solve"):
                c.close(got[k], cell["arms"][arm][k], f"{name} {arm} {k}")
            res[(name, arm)] = got
        m = cell["memory"]
        entries = m["raw"]
        c.eq(len(entries), 48, f"{name} memory entries")
        c.eq(verify_entries(entries, pubs), [], f"{name} memory chain+signatures")
        c.eq(m["chain_valid"], not verify_entries(entries, pubs), f"{name} chain flag")
        ok, solved = replay_exact(entries, ds[0])
        c.eq(ok, True, f"{name} exact arm replays from memory")
        c.eq(solved, m["replay_solved"], f"{name} replay solved")
        c.eq(m["replay_ok"], True, f"{name} replay flag")
        c.eq(m["live_solved"], solved, f"{name} live == replay")
        c.eq(m["tenant_probe"]["foreign_visible_to_us"], 0, f"{name} tenant isolation")
        c.eq(m["tamper_detected"], True, f"{name} tamper detected")
        c.ok(all(not p["granted"] for p in m["authority_probes"]), f"{name} no authority")

    def a(s, arm):
        return res[(s, arm)]

    h1 = all(a(s, "exact")["solved_mean"] >= 19 and a(s, "no_handoff")["solved_mean"] <= 15
             and a(s, "exact")["cost_mean"] <= 50 and a(s, "no_handoff")["cost_mean"] >= 70
             for s in ("salt1", "salt2"))
    c.ok(h1, "H1 handoff dividend")
    h2 = all(a(s, "hash")["solved_mean"] <= 15 and a(s, "summary8")["solved_mean"] <= 3
             and a(s, "exact")["solved_mean"] - a(s, "hash")["solved_mean"] >= 6
             for s in ("salt1", "salt2"))
    c.ok(h2, "H2 exact state required")
    h3 = all(a(s, "churn_exact")["solved_mean"] >= 19 and a(s, "churn_no_handoff")["solved_mean"] <= 15
             for s in ("salt1", "salt2"))
    c.ok(h3, "H3 churn")
    h4 = all(a(s, "poison_trust")["solved_mean"] <= 3 and a(s, "poison_verified")["solved_mean"] >= 10
             and a(s, "poison_verified")["solved_mean"] - a(s, "poison_trust")["solved_mean"] >= 8
             for s in ("salt1", "salt2"))
    c.ok(h4, "H4 verify the handoff")
    h5 = all(all(a(s, arm)["cost_mean"] <= BUDGET for arm in ARMS)
             and a(s, "stage1_only")["solved_mean"] == 0
             and a(s, "stage2_only")["solved_mean"] == 0 for s in ("salt1", "salt2"))
    c.ok(h5, "H5 budget and both stages")
    c.eq(rep["drill"]["distinct_pids"], 4, "drill distinct PIDs")
    c.eq(rep["drill"]["chain_valid"], True, "drill chain valid")
    c.eq(rep["verdict"], "HANDOFF_DIVIDEND_SUPPORTED", "verdict")
    for k in ("H1_handoff_dividend", "H2_exact_state_required", "H3_churn",
              "H4_verify_the_handoff", "H5_budget_and_both_stages", "H6_governance"):
        c.eq(rep["hypotheses"][k]["verdict"], "SUPPORTED", f"{k} verdict")
    c.eq(rep["hypotheses"]["H7_external_review"]["verdict"], "BLOCKED", "H7 verdict")
    return c


def main():
    root = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path(__file__).resolve().parent
    c = verify(root)
    if c.bad:
        print("HDO VERIFICATION FAILED")
        for b in c.bad[:20]:
            print(" -", b)
        return 1
    print(f"HDO VERIFIED {c.n}/{c.n} checks; {STATUS}")
    return 0


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