#!/usr/bin/env python3
"""OSCH standalone auditor — replays the whole campaign from the revealed salts.

Imports no CAIN code. It rebuilds the task batteries, the proposal/claim/audit streams, the nine
arms, every governed-memory entry (hash, signature, chain) and recomputes every hypothesis and the
verdict. Usage: python3 verify_osch_offline.py <bundle-dir>
"""
from __future__ import annotations

import hashlib
import itertools
import json
import math
import sys
from pathlib import Path

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

FEATURES = 8
FAMILIES = (2, 3, 4, 5)
TASKS_PER_FAMILY = 24
MISSIONS = 3
BUDGET = 192
AGENTS = ("A0", "A1", "A2", "A3", "A4", "A5")
WEAK = "A4"
INSIDER = "mallory"
VERIFIER = "verifier"
AUDITOR = "auditor"
TENANT = "cain42-osch"
SEED = "osch"
P = {
    "A0": {2: 0.55, 3: 0.12, 4: 0.10, 5: 0.09},
    "A1": {2: 0.18, 3: 0.50, 4: 0.12, 5: 0.11},
    "A2": {2: 0.14, 3: 0.16, 4: 0.45, 5: 0.13},
    "A3": {2: 0.10, 3: 0.13, 4: 0.14, 5: 0.42},
    "A4": {2: 0.12, 3: 0.10, 4: 0.11, 5: 0.10},
    "A5": {2: 0.15, 3: 0.11, 4: 0.13, 5: 0.12},
}
BEST = {f: max(AGENTS, key=lambda a: (P[a][f], a)) for f in FAMILIES}
ARMS = ("ORACLE", "ROUND_ROBIN", "RANDOM", "NO_MEMORY", "BEST_GLOBAL",
        "RELIABILITY", "COMMIT", "AMNESIAC", "TRUST", "AUDITED")
MEMORY_ARMS = ("BEST_GLOBAL", "RELIABILITY", "COMMIT", "AMNESIAC", "TRUST", "AUDITED")
NO_MEMORY_BLOCK = BUDGET // len(AGENTS)


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(s):
    return int.from_bytes(hashlib.sha256(s.encode()).digest()[:8], "big") / 2 ** 64


def _rules(k):
    out = []
    for feats in itertools.combinations(range(FEATURES), k):
        for signs in itertools.product((True, False), repeat=k):
            out.append(tuple(sorted((f, sg) for f, sg in zip(feats, signs))))
    return tuple(out)


RULES = {k: _rules(k) for k in FAMILIES}


def target(salt, mission, f, j):
    r = RULES[f]
    i = int(hashlib.sha256(f"osch-target|{salt}|{mission}|{f}|{j}".encode()).hexdigest()[:16], 16)
    return r[i % len(r)]


def attempt(salt, mission, f, j, a, k):
    t = target(salt, mission, f, j)
    hit = u(f"osch-propose|{salt}|{mission}|{f}|{j}|{a}|{k}") < P[a][f]
    if hit:
        prop = t
    else:
        rs = RULES[f]
        i = int(hashlib.sha256(f"osch-decoy|{salt}|{mission}|{f}|{j}|{a}|{k}".encode()).hexdigest()[:16], 16) % len(rs)
        if rs[i] == t:
            i = (i + 1) % len(rs)
        prop = rs[i]
    return hit, sha(canon(prop))[:16], sha(canon(t))[:16]


def claim(salt, mission, f, j, a, k):
    return a == WEAK and u(f"osch-claim|{salt}|{mission}|{f}|{j}|{k}") < 1.0


def audited(salt, mission, f, j, a, k):
    return u(f"osch-audit|{salt}|{mission}|{f}|{j}|{k}") < 0.25


def rnd(salt, mission, i, field, n):
    return int(hashlib.sha256(f"osch-random|{salt}|{mission}|{i}|{field}".encode()).hexdigest()[:16], 16) % n


def ucb(mean, n, total):
    return mean + math.sqrt(2.0 * math.log(max(total, 1) + 2.0) / (n + 1.0))


class State:
    def __init__(self):
        self.n, self.s, self.total, self.attempts = {}, {}, 0, {}
        self.solved = {f: set() for f in FAMILIES}
        self.q = set()

    def cell(self, a, f):
        return self.s.get((a, f), 0), self.n.get((a, f), 0)

    def bump(self, a, f, y):
        self.s[(a, f)] = self.s.get((a, f), 0) + (1 if y else 0)
        self.n[(a, f)] = self.n.get((a, f), 0) + 1
        self.total += 1

    def mean(self, a, f):
        s, n = self.cell(a, f)
        return (s + 1.0) / (n + 2.0)


def least(st, f, tasks=None):
    pool = list(tasks if tasks is not None else range(TASKS_PER_FAMILY))
    uns = [j for j in pool if j not in st.solved[f]] or [j for j in range(TASKS_PER_FAMILY) if j not in st.solved[f]]
    return min(uns, key=lambda j: (st.attempts.get((f, j), 0), j))


def choose(st, arm, salt, mission, i):
    fams = [f for f in FAMILIES if len(st.solved[f]) < TASKS_PER_FAMILY]
    if not fams:
        return None
    if arm == "ORACLE":
        sc, f, a = max((P[a][f], f, a) for a in AGENTS for f in fams)
        return a, f, least(st, f)
    if arm == "ROUND_ROBIN":
        f = fams[(i // len(AGENTS)) % len(fams)]
        return AGENTS[i % len(AGENTS)], f, least(st, f)
    if arm == "RANDOM":
        f = fams[rnd(salt, mission, i, "family", len(fams))]
        a = AGENTS[rnd(salt, mission, i, "agent", len(AGENTS))]
        return a, f, least(st, f)
    if arm == "NO_MEMORY":
        q = min(i // NO_MEMORY_BLOCK, len(AGENTS) - 1)
        a = AGENTS[q]
        own = [j for j in range(TASKS_PER_FAMILY) if j % len(AGENTS) == q]
        un = [f for f in FAMILIES if any(j not in st.solved[f] for j in own)] or fams
        f = un[0]
        return a, f, least(st, f, own)
    if arm == "BEST_GLOBAL":
        def sc(x):
            s = sum(v for (aa, _f), v in st.s.items() if aa == x)
            n = sum(v for (aa, _f), v in st.n.items() if aa == x)
            return ucb((s + 1.0) / (n + 2.0), n, st.total)
        a = max(AGENTS, key=lambda x: (sc(x), x))
        f = max(fams, key=lambda x: (TASKS_PER_FAMILY - len(st.solved[x]), -x))
        return a, f, least(st, f)
    committed = arm in ("COMMIT", "TRUST", "AUDITED") and all(st.cell(a, f)[1] >= 2 for a in AGENTS for f in fams)

    def cs(a, f):
        s, n = st.cell(a, f)
        return (s + 1.0) / (n + 2.0) if committed else ucb((s + 1.0) / (n + 2.0), n, st.total)
    sc, nf, a, f = max((cs(a, f), -f, a, f) for a in AGENTS for f in fams)
    return a, f, least(st, f)


def key(agent):
    return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{agent}".encode()).digest())


def replay(salt, arm):
    st = State()
    missions, rows, entries = [], [], []
    seq = 0
    prev = ""

    def write(agent, kind, k, value):
        nonlocal seq, prev
        seq += 1
        n = sha(canon({"agent": agent, "kind": kind, "key": k, "value": value}))[:16]
        payload = {"seq": seq, "tenant": TENANT, "agent": agent, "kind": kind, "key": k,
                   "value": value, "prev": prev, "nonce": n, "created_at": seq / 1000.0,
                   "grants_authority": False, "executable": False}
        body = canon(payload)
        sig = key(agent).sign(body).hex()
        h = sha(prev.encode() + body + bytes.fromhex(sig))
        prev = h
        entries.append(payload)

    for m in range(1, MISSIONS + 1):
        if arm == "AMNESIAC":
            st.n, st.s, st.total = {}, {}, 0
        st.solved = {f: set() for f in FAMILIES}
        st.attempts = {}
        mrow, h = [], hashlib.sha256()
        for i in range(BUDGET):
            if all(len(st.solved[f]) >= TASKS_PER_FAMILY for f in FAMILIES):
                break
            pk = choose(st, arm, salt, m, i)
            if pk is None:
                break
            a, f, j = pk
            k = st.attempts.get((f, j), 0)
            y, ph, th = attempt(salt, m, f, j, a, k)
            phat = P[a][f] if arm == "ORACLE" else st.mean(a, f)
            r = {"i": i, "a": a, "f": f, "j": j, "k": k, "y": bool(y),
                 "phat": round(phat, 6), "proposal": ph, "target": th}
            h.update(canon({x: r[x] for x in ("i", "a", "f", "j", "k", "y", "phat", "proposal", "target")}))
            cn = (not y) and a == WEAK and claim(salt, m, f, j, a, k)
            if arm in MEMORY_ARMS:
                write(a, "proposal", f"{m}:{f}:{j}:{k}",
                      {"agent": a, "family": f, "task": j, "attempt": k, "proposal": ph, "target": th})
                write(VERIFIER, "outcome", f"{m}:{f}:{j}:{k}",
                      {"agent": a, "family": f, "task": j, "attempt": k, "success": bool(y)})
                if arm in ("TRUST", "AUDITED") and cn:
                    write(INSIDER, "claim", f"{m}:{f}:{j}:{k}",
                          {"agent": a, "family": f, "task": j, "attempt": k, "success": True})
                    if arm == "AUDITED" and audited(salt, m, f, j, a, k):
                        write(AUDITOR, "contradiction", f"{m}:{f}:{j}:{k}",
                              {"agent": a, "family": f, "task": j, "attempt": k,
                               "claimed": True, "actual": bool(y)})
                        if a not in st.q:
                            write(AUDITOR, "quarantine", f"{m}:{a}", {"agent": a, "reason": "CONTRADICTED_CLAIM"})
                            st.q.add(a)
            learned = y
            if arm == "TRUST":
                learned = bool(y or cn)
            elif arm == "AUDITED":
                learned = bool(y) if (cn and (audited(salt, m, f, j, a, k) or a in st.q)) else bool(y or cn)
            st.bump(a, f, learned)
            st.attempts[(f, j)] = k + 1
            if y:
                st.solved[f].add(j)
            mrow.append(r)
        used = len(mrow)
        solved = sum(len(v) for v in st.solved.values())
        brier = sum((r["phat"] - (1.0 if r["y"] else 0.0)) ** 2 for r in mrow) / used if used else 0.0
        mis = sum(1 for r in mrow if P[BEST[r["f"]]][r["f"]] - P[r["a"]][r["f"]] > 0.10)
        missions.append({"arm": arm, "salt": salt, "mission": m, "budget": BUDGET,
                         "attempts_used": used, "solved": solved,
                         "tasks": len(FAMILIES) * TASKS_PER_FAMILY,
                         "yield": round(solved / used, 6) if used else 0.0,
                         "brier": round(brier, 6),
                         "misalloc": round(mis / used, 6) if used else 0.0,
                         "solved_by_family": {str(f): len(st.solved[f]) for f in FAMILIES},
                         "stream_digest": h.hexdigest(),
                         "memory": ({"tenant": TENANT, "count": len(entries), "head": prev,
                                     "kinds": _kinds(entries), "agents": sorted({e["agent"] for e in entries})}
                                    if arm in MEMORY_ARMS else None),
                         "quarantined": sorted(st.q)})
        rows.extend(mrow)
    return missions, rows, entries


def _kinds(entries):
    out = {}
    for e in entries:
        out[e["kind"]] = out.get(e["kind"], 0) + 1
    return out


def arms_summary(replayed, label):
    out = {}
    for arm in ARMS:
        ms, rows, ent = replayed[arm]
        used = sum(m["attempts_used"] for m in ms)
        solved = sum(m["solved"] for m in ms)
        out[arm] = {"missions": ms, "rows": rows,
                    "totals": {"solved": solved, "attempts": used,
                               "yield": round(solved / max(1, used), 6),
                               "brier": round(sum(m["brier"] * m["attempts_used"] for m in ms) / max(1, used), 6),
                               "misalloc": round(sum(m["misalloc"] * m["attempts_used"] for m in ms) / max(1, used), 6)},
                    "entries": ent}
    return out


def hypotheses(a, b):
    H = {}
    ok = True
    for salt in ("salt1", "salt2"):
        pass
    # H1
    ok = True
    d1 = {}
    for salt, A in (("salt1", a), ("salt2", b)):
        cm = [m["solved"] for m in A["COMMIT"]["missions"]]
        rr = [m["solved"] for m in A["ROUND_ROBIN"]["missions"]]
        rd = [m["solved"] for m in A["RANDOM"]["missions"]]
        w = all(c > x and c > y for c, x, y in zip(cm, rr, rd))
        d1[salt] = {"commit": cm, "round_robin": rr, "random": rd, "all_missions": w}
        ok = ok and w
    H["H1_scheduler_beats_uniform"] = {"detail": d1, "ok": ok}
    # H2
    ok, d2 = True, {}
    for salt, A in (("salt1", a), ("salt2", b)):
        c, o, r = A["COMMIT"]["totals"]["solved"], A["ORACLE"]["totals"]["solved"], A["ROUND_ROBIN"]["totals"]["solved"]
        frac = c / o if o else 0.0
        d2[salt] = {"commit": c, "oracle": o, "round_robin": r, "fraction_of_oracle": round(frac, 4),
                    "oracle_advantage_recovered": round((c - r) / (o - r), 4) if o > r else 0.0}
        ok = ok and frac >= 0.70
    H["H2_oracle_recovery"] = {"detail": d2, "ok": ok}
    # H3
    ok, d3 = True, {}
    for salt, A in (("salt1", a), ("salt2", b)):
        cm = [m["solved"] for m in A["COMMIT"]["missions"]]
        bg = [m["solved"] for m in A["BEST_GLOBAL"]["missions"]]
        w = all(c > x for c, x in zip(cm, bg))
        d3[salt] = {"commit": cm, "best_global": bg, "all_missions": w}
        ok = ok and w
    H["H3_family_routing"] = {"detail": d3, "ok": ok}
    # H4
    ok, d4 = True, {}
    for salt, A in (("salt1", a), ("salt2", b)):
        cm = A["COMMIT"]["missions"]
        am = A["AMNESIAC"]["missions"]
        y1 = cm[0]["yield"]
        y23 = (cm[1]["solved"] + cm[2]["solved"]) / max(1, cm[1]["attempts_used"] + cm[2]["attempts_used"])
        gain = y23 / y1 if y1 else 0.0
        m3 = cm[2]["solved"] > am[2]["solved"]
        d4[salt] = {"yield_m1": round(y1, 4), "yield_m2_3": round(y23, 4), "gain": round(gain, 4),
                    "m3_commit": cm[2]["solved"], "m3_amnesiac": am[2]["solved"], "m3_beats_amnesiac": m3}
        ok = ok and gain >= 1.10 and m3
    H["H4_memory_carries_adaptation"] = {"detail": d4, "ok": ok}
    # H5
    ok, d5 = True, {}
    for salt, A in (("salt1", a), ("salt2", b)):
        c, t, ad = A["COMMIT"]["totals"]["solved"], A["TRUST"]["totals"]["solved"], A["AUDITED"]["totals"]["solved"]
        frac = ad / c if c else 0.0
        d5[salt] = {"commit": c, "trust_claims": t, "audited": ad, "audited_fraction": round(frac, 4)}
        ok = ok and t < c and frac >= 0.80
    H["H5_claim_boundary"] = {"detail": d5, "ok": ok}
    # H6  (the auditor re-derives the chain; the published head binds every stored signature)
    ok, d6 = True, {}
    for salt, A in (("salt1", a), ("salt2", b)):
        for arm in MEMORY_ARMS:
            ent = A[arm]["entries"]
            prev, bad = "", 0
            for e in ent:
                if e["prev"] != prev or e["tenant"] != TENANT or e["grants_authority"] or e["executable"]:
                    bad += 1
                body = canon(e)
                prev = sha(e["prev"].encode() + body + bytes.fromhex(key(e["agent"]).sign(body).hex()))
            head_ok = bool(ent) and prev == A[arm]["missions"][-1]["memory"]["head"]
            d6[f"{salt}:{arm}"] = {"entries": len(ent), "bad_links": bad, "head_ok": head_ok}
            ok = ok and bad == 0 and head_ok
    H["H6_integrity_and_no_authority"] = {"detail": d6, "ok": ok}
    # H7
    ok, d7 = True, {}
    for salt, A in (("salt1", a), ("salt2", b)):
        t, rr = A["TRUST"]["totals"]["solved"], A["ROUND_ROBIN"]["totals"]["solved"]
        d7[salt] = {"trust_claims": t, "round_robin": rr, "no_memory": A["NO_MEMORY"]["totals"]["solved"]}
        ok = ok and t < rr
    H["H7_unverified_memory_worse_than_none"] = {"detail": d7, "ok": ok}
    # H8
    ok, d8 = True, {}
    for salt, A in (("salt1", a), ("salt2", b)):
        c, r = A["COMMIT"]["totals"]["solved"], A["RELIABILITY"]["totals"]["solved"]
        d8[salt] = {"commit": c, "ucb1": r, "delta": c - r}
        ok = ok and c > r
    H["H8_commit_beats_ucb1"] = {"detail": d8, "ok": ok}
    H["H9_external_review"] = {"verdict": "BLOCKED", "ok": True}
    verdict = "ORGANISM_SCHEDULER_SUPPORTED" if all(v["ok"] for v in H.values()) else "NOT_SUPPORTED"
    return H, verdict


def merkle(files):
    l = sorted(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():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    rep = json.loads((d / "OSCH_RUN_REPORT.json").read_text())
    rows_file = json.loads((d / "OSCH_ROWS.json").read_text())
    sal = json.loads((d / "SALTS.json").read_text())
    checks = []

    def ck(name, ok):
        checks.append((name, bool(ok)))

    replayed = {label: {a: replay(sal[label], a) for a in ARMS} for label in ("salt1", "salt2")}
    for label in ("salt1", "salt2"):
        A = arms_summary(replayed[label], label)
        repA = rep["arms"][label]
        for arm in ARMS:
            ms, rows, ent = replayed[label][arm]
            ck(f"{label}:{arm}:mission_count", len(ms) == len(repA[arm]["missions"]))
            for k in range(len(ms)):
                r = repA[arm]["missions"][k]
                for field in ("solved", "attempts_used", "yield", "brier", "misalloc", "stream_digest"):
                    ck(f"{label}:{arm}:m{k+1}:{field}", r[field] == ms[k][field])
                ck(f"{label}:{arm}:m{k+1}:mem", r["memory"] == ms[k]["memory"])
            ck(f"{label}:{arm}:rows_len", len(rows) == len(rows_file[label][arm]))
            ck(f"{label}:{arm}:rows_digest", sha(canon(rows_file[label][arm])) == sha(canon(rows)))
            if arm in MEMORY_ARMS:
                ck(f"{label}:{arm}:entries", len(ent) == repA[arm]["probe"]["entries"])
                ck(f"{label}:{arm}:head",
                   ent[-1] and sha(ent[-1]["prev"].encode() + canon(ent[-1]) +
                                   bytes.fromhex(key(ent[-1]["agent"]).sign(canon(ent[-1])).hex())) ==
                   ms[-1]["memory"]["head"])
                pr = repA[arm]["probe"]
                ck(f"{label}:{arm}:probe",
                   bool(pr) and pr.get("all_pass") is True and pr.get("chain_and_signatures") is True
                   and pr.get("every_entry_no_authority") is True and pr.get("replay_refused") is True
                   and pr.get("tamper_detected") is True and pr.get("authority_from_memory_refused") is True
                   and pr.get("reason") == "AUTHORITY_FROM_MEMORY_REFUSED"
                   and pr.get("entries") == len(ent))
            # the public measurements block must agree with the replay
            mm = rep["measurements"][label][arm]
            ck(f"{label}:{arm}:meas_missions", mm["missions"] == [m["solved"] for m in ms])
            ck(f"{label}:{arm}:meas_totals", json.loads(json.dumps(mm["totals"], sort_keys=True)) ==
               json.loads(json.dumps(A[arm]["totals"], sort_keys=True)))
            ck(f"{label}:{arm}:meas_brier", mm["brier"] == A[arm]["totals"]["brier"])
            ck(f"{label}:{arm}:meas_misalloc", mm["misalloc"] == A[arm]["totals"]["misalloc"])
            ck(f"{label}:{arm}:meas_entries", mm["memory_entries"] == len(ent))
    H, verdict = hypotheses(arms_summary(replayed["salt1"], "salt1"),
                            arms_summary(replayed["salt2"], "salt2"))
    ck("verdict", verdict == rep["verdict"])
    for k, v in H.items():
        ck(f"hyp:{k}", (rep["hypotheses"].get(k, {}).get("verdict") or "BLOCKED") ==
           (v.get("verdict") or ("SUPPORTED" if v["ok"] else "NOT_SUPPORTED")))
        if "detail" in v and k != "H6_integrity_and_no_authority":
            ck(f"hyp_detail:{k}", json.loads(json.dumps(v["detail"], sort_keys=True)) ==
               json.loads(json.dumps(rep["hypotheses"][k]["detail"], sort_keys=True)))
    # salts commitment: the revealed salt must hash to the pre-committed value
    pre = json.loads((d / "OSCH_PREREGISTRATION.json").read_text())
    for k in ("salt1", "salt2"):
        ck(f"{k}_commitment", sha(sal[k].encode()) == pre["salts_commitment"][k])
    # manifest
    man = json.loads((d / "MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey as Pub
    try:
        Pub.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        ck("manifest_signature", True)
    except Exception:
        ck("manifest_signature", False)
    for name, h in man["files"].items():
        p = d / name
        ck(f"file:{name}", p.exists() and sha(p.read_bytes()) == h)
    ck("merkle_root", merkle([sha((d / n).read_bytes()) for n in man["files"]]) == man["merkle_root"])
    ck("no_engine_source", not any(x.name.endswith((".py",)) and x.name not in ("verify_osch_offline.py",)
                                  for x in d.rglob("*") if x.is_file()))
    bad = [n for n, ok in checks if not ok]
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    for n in bad[:20]:
        print("FAIL", n)
    return 0 if not bad else 1


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