#!/usr/bin/env python3
"""Standalone auditor for CSG — curriculum supply governance.  Imports no CAIN code.

  python3 verify_supply_offline.py <bundle-dir>

Re-checks the signed manifest, every file hash, every governed-memory entry (signature, chain, nonce,
tenant, no authority), then **re-derives the whole campaign from the revealed salts**: primitives,
shards, pool, blocks, sealed set, the hijacking proposal stream, every veto, every attempt, the
captured-shard forgeries, every hypothesis and the verdict.
"""
import hashlib
import json
import random
import sys
from pathlib import Path

N = 10
IDENT = tuple(range(N))
SHARDS = 4
AGENTS = ["alpha", "beta", "gamma", "delta"]
HONEST = {"alpha"}
GENS = 3
PER_AGENT = 5
BAD_REACH = 0.7
QUOTA = 0.30
TENANT = "cain42-supply"
S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
FAIL = []


def sha(b):
    return hashlib.sha256(b).hexdigest()


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


def check(name, ok, detail=""):
    if not ok:
        FAIL.append(name)
    print(("PASS " if ok else "FAIL ") + name + (f" — {detail}" if detail else ""))
    return ok


def compose(f, g):
    return tuple(f[g[i]] for i in range(N))


def word_fn(word, prims):
    f = IDENT
    for i in word:
        f = compose(prims[i], f)
    return f


def bid(f):
    return "".join("0123456789"[x] for x in f)


def rand_perm(rng):
    p = list(range(N))
    rng.shuffle(p)
    return tuple(p)


def primitives(salt):
    rng = random.Random(int(sha(f"{salt}|prims".encode()), 16))
    out, seen = [], set()
    while len(out) < 6:
        p = rand_perm(rng)
        if p == IDENT or p in seen:
            continue
        seen.add(p)
        out.append(p)
    return out


def rng_of(salt, label):
    return random.Random(int(sha(f"{salt}|{label}".encode()), 16))


def build_world(salt):
    prims = primitives(salt)
    seen = {bid(f) for f in prims}
    pairs = []
    for i in range(6):
        for j in range(6):
            f = word_fn([i, j], prims)
            if bid(f) in seen:
                continue
            seen.add(bid(f))
            pairs.append({"word": [i, j], "fn": f, "steps": 2, "shard": len(pairs) % SHARDS})
    pair_shard = {bid(p["fn"]): p["shard"] for p in pairs}
    key, rng, tries = [], rng_of(salt, "key3"), 0
    while len(key) < 24 and tries < 100000:
        tries += 1
        i, j, k = (rng.randrange(6) for _ in range(3))
        w = [i, j, k]
        f = word_fn(w, prims)
        if bid(f) in seen or f in prims:
            continue
        pre = bid(word_fn([i, j], prims))
        suf = bid(word_fn([j, k], prims))
        shard = len(key) % SHARDS
        if pre not in pair_shard or suf not in pair_shard:
            continue
        if pair_shard[pre] == shard or pair_shard[suf] == shard:
            continue
        seen.add(bid(f))
        key.append({"word": w, "fn": f, "steps": 3, "shard": shard, "prefix": pre, "suffix": suf})
    pairs6, tries = [], 0
    while len(pairs6) < 90 and tries < 100000:
        tries += 1
        a = key[rng.randrange(len(key))]
        b = key[rng.randrange(len(key))]
        w = a["word"] + b["word"]
        f = word_fn(w, prims)
        if bid(f) in seen:
            continue
        seen.add(bid(f))
        pairs6.append({"word": w, "fn": f, "steps": 6, "shard": len(pairs6) % SHARDS})
    pool = pairs + key + pairs6
    for i, t in enumerate(pool):
        t["id"] = f"task-{i:03d}"
    sealed, tries = [], 0
    while len(sealed) < 24 and tries < 100000:
        tries += 1
        r = rng_of(salt, f"sealed-{tries}")
        a = key[r.randrange(len(key))]
        b = key[r.randrange(len(key))]
        if a["shard"] == b["shard"]:
            continue
        w = a["word"] + b["word"]
        f = word_fn(w, prims)
        if bid(f) in seen:
            continue
        seen.add(bid(f))
        sealed.append({"id": f"sealed-{len(sealed):02d}", "word": w, "fn": f, "steps": 6,
                       "shards": [a["shard"], b["shard"]]})
    return {"primitives": prims, "key": key, "pool": pool, "sealed": sealed}


class Reach:
    def __init__(self, prims):
        self.singles = set(prims)
        self.all = set(prims)
        for f in prims:
            for g in prims:
                self.all.add(compose(f, g))

    def add(self, f):
        if f in self.singles:
            return
        new = {f}
        for g in self.singles:
            new.add(compose(f, g))
            new.add(compose(g, f))
        self.singles.add(f)
        self.all |= new

    def has(self, f):
        return f in self.all


class Library:
    def __init__(self, prims):
        self.by_bid, self.entries = {}, []
        for i, f in enumerate(prims):
            self.by_bid[bid(f)] = f
            self.entries.append({"fn": f, "steps": 1, "owner": "primitive",
                                 "task_id": f"prim-{i}", "word": [i]})
        self.reach = Reach(prims)

    def has(self, f):
        return bid(f) in self.by_bid

    def admit(self, fn, steps, owner, task_id, word):
        k = bid(fn)
        if k in self.by_bid:
            return False
        self.by_bid[k] = fn
        self.entries.append({"fn": fn, "steps": steps, "owner": owner, "task_id": task_id,
                             "word": list(word)})
        self.reach.add(fn)
        return True


def best(pool, lib, solved, shard):
    mine = [t for t in pool if t["shard"] == shard and t["id"] not in solved and lib.reach.has(t["fn"])]
    if not mine:
        return None
    unsolved = {bid(t["fn"]) for t in pool if t["id"] not in solved}
    out, key = None, None
    for c in mine:
        unlocked = set()
        for g in lib.reach.singles:
            for h in (compose(c["fn"], g), compose(g, c["fn"])):
                if h in unsolved:
                    unlocked.add(bid(h))
        k = (len(unlocked), -c["steps"], c["id"])
        if key is None or k > key:
            out, key = c, k
    return out


def proposal(agent, pool, lib, solved, shard, rng, honest):
    if honest:
        return best(pool, lib, solved, shard)
    mine = [t for t in pool if t["shard"] == shard]
    if not mine:
        return None
    unreachable = [t for t in mine if t["id"] not in solved and not lib.reach.has(t["fn"])]
    already = [t for t in mine if t["id"] in solved]
    if rng.random() < BAD_REACH and unreachable:
        return max(unreachable, key=lambda t: (t["steps"], t["id"]))
    if already:
        return rng.choice(already)
    if unreachable:
        return max(unreachable, key=lambda t: (t["steps"], t["id"]))
    return rng.choice(mine)


def gate(veto, task, lib, solved, used, budget, insider):
    if task is None:
        return None, "no_proposal"
    if veto == "NONE":
        return task, "accept"
    if veto == "REACH":
        return (task, "accept") if lib.reach.has(task["fn"]) else (None, "fallback_unreachable")
    if veto == "VALUE":
        if not lib.reach.has(task["fn"]):
            return None, "fallback_unreachable"
        if task["id"] in solved or lib.has(task["fn"]):
            return None, "fallback_known"
        return task, "accept"
    if veto == "QUOTA":
        if insider and used >= QUOTA * budget:
            return None, "fallback_quota"
        return task, "accept"
    if veto == "VALUE_QUOTA":
        if insider and used >= QUOTA * budget:
            return None, "fallback_quota"
        if not lib.reach.has(task["fn"]):
            return None, "fallback_unreachable"
        if task["id"] in solved or lib.has(task["fn"]):
            return None, "fallback_known"
        return task, "accept"
    return task, "accept"


def sealed_score(lib, sealed):
    return len([s for s in sealed if lib.reach.has(s["fn"])])


def replay(salt, world, veto, shared, oracle, poison, verified):
    prims, pool, sealed = world["primitives"], world["pool"], world["sealed"]
    if shared:
        one = Library(prims)
        libs = {a: one for a in AGENTS}
        ss = set()
        solved = {a: ss for a in AGENTS}
    else:
        libs = {a: Library(prims) for a in AGENTS}
        solved = {a: set() for a in AGENTS}
    budget = GENS * PER_AGENT * len(AGENTS)
    used = 0
    stats = {"accept": 0, "accepted": 0, "fallback_unreachable": 0, "fallback_known": 0,
             "fallback_quota": 0, "no_proposal": 0, "insider_accepted": 0}
    rows, curve, admitted, poisoned, rejected = [], [], 0, 0, 0
    poison_pairs = []
    if poison:
        cands = [t for t in world["key"] if t["shard"] == 0 and not libs["alpha"].has(t["fn"])]

        def freq(b):
            return sum(1 for t in pool if t["steps"] == 6 and
                       (t["word"][:3] == b["word"] or t["word"][3:] == b["word"]))

        for pt in sorted(cands, key=lambda b: (-freq(b), b["id"])):
            ww = None
            for i in range(6):
                for j in range(6):
                    for k in range(6):
                        w = [i, j, k]
                        f = word_fn(w, prims)
                        if f != pt["fn"] and f not in prims:
                            ww = w
                            break
                    if ww:
                        break
                if ww:
                    break
            if ww:
                poison_pairs.append((pt, ww))
    for gen in range(GENS):
        if poison and gen == 0:
            target = libs["alpha"]
            for pt, ww in poison_pairs:
                wrong_fn = word_fn(ww, prims)
                true_id = bid(pt["fn"])
                if verified:
                    if wrong_fn != pt["fn"]:
                        rejected += 1
                elif true_id not in target.by_bid:
                    target.by_bid[true_id] = wrong_fn
                    target.entries.append({"fn": wrong_fn, "steps": 3, "owner": "mallory",
                                           "task_id": pt["id"], "word": ww})
                    target.reach.add(wrong_fn)
                    poisoned += 1
        for ai, agent in enumerate(AGENTS):
            lib = libs[agent]
            for attempt in range(PER_AGENT):
                rng = random.Random(f"{salt}|{gen}|{ai}|{attempt}|{veto}")
                insider = (agent not in HONEST) and not oracle
                task = proposal(agent, pool, lib, solved[agent], ai % SHARDS, rng, not insider)
                decision, reason = gate(veto, task, lib, solved[agent], used, budget, insider)
                stats[reason] += 1
                if decision is None:
                    decision = best(pool, lib, solved[agent], ai % SHARDS)
                    if decision is not None:
                        stats["accepted"] += 1
                        if insider:
                            stats["insider_accepted"] += 1
                            used += 1
                else:
                    stats["accepted"] += 1
                    if insider:
                        stats["insider_accepted"] += 1
                        used += 1
                if decision is None:
                    rows.append({"gen": gen, "attempt": attempt, "agent": agent, "task": None,
                                 "solved": False, "steps": 0, "reason": reason})
                    continue
                ok = lib.reach.has(decision["fn"])
                if ok:
                    if lib.admit(decision["fn"], decision["steps"], agent, decision["id"],
                                 decision["word"]):
                        admitted += 1
                    solved[agent].add(decision["id"])
                rows.append({"gen": gen, "attempt": attempt, "agent": agent,
                             "task": decision["id"], "solved": ok, "steps": decision["steps"],
                             "reason": reason})
        n = sealed_score(libs["alpha"], sealed) if shared else max(
            sealed_score(l, sealed) for l in libs.values())
        curve.append({"gen": gen, "solved": n, "of": len(sealed),
                      "library": len(libs["alpha"].entries)})
    return {"sealed_curve": curve, "admitted": admitted, "poisoned": poisoned,
            "rejected": rejected, "stats": stats, "rows": rows,
            "library_size": len(libs["alpha"].entries) if shared else 0}


ARMS = [
    ("ORACLE", "NONE", True, True, False, True),
    ("TRUST", "NONE", True, False, False, True),
    ("QUOTA", "QUOTA", True, False, False, True),
    ("VETO_REACH", "REACH", True, False, False, True),
    ("VETO_VALUE", "VALUE", True, False, False, True),
    ("VALUE_QUOTA", "VALUE_QUOTA", True, False, False, True),
    ("ISOLATED", "VALUE", False, False, False, True),
    ("VERIFIED_POISON", "VALUE", True, False, True, True),
    ("UNVERIFIED", "VALUE", True, False, True, False),
]


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


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    man = json.loads((d / "MANIFEST.json").read_text())
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        check("manifest_signature", True)
    except Exception as exc:
        check("manifest_signature", False, str(exc))
    files = {k: sha((d / k).read_bytes()) for k in man["files"]}
    check("file_hashes", files == man["files"])
    leaves = sorted(man["files"].values())
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    check("merkle_root", (leaves[0] if leaves else sha(b"")) == man["merkle_root"])
    check("merkle_file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])
    check("engine_withheld", man.get("engine_withheld") is True)
    check("no_engine_source", not [p.name for p in d.glob("*.py") if p.name != Path(__file__).name])

    rep = json.loads((d / "CURRICULUM_SUPPLY_RUN_REPORT.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())
    pre = json.loads((d / "CURRICULUM_SUPPLY_PREREGISTRATION.json").read_text())
    check("salt_commitment", all(pre["salts_commitment"][k] == sha(v.encode()) for k, v in salts.items()))
    check("status_line", rep["status"] == S)
    check("no_model_calls", rep["design"]["model_calls"] == 0)
    mem = json.loads((d / "CURRICULUM_SUPPLY_MEMORY.json").read_text())
    bad, entries = [], 0
    for m in mem:
        prev = ""
        for e in m["entries"]:
            entries += 1
            body_e = canon({k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value",
                                              "prev", "nonce", "created_at", "grants_authority",
                                              "executable")})
            ok = (e["tenant"] == TENANT and e["prev"] == prev and e["grants_authority"] is False
                  and e["executable"] is False
                  and sha(e["prev"].encode() + body_e + bytes.fromhex(e["sig"])) == e["hash"]
                  and e["nonce"] == nonce(e["agent"], e["kind"], e["key"], e["value"]))
            if ok:
                try:
                    Ed25519PublicKey.from_public_bytes(bytes.fromhex(m["pubs"][e["agent"]])).verify(
                        bytes.fromhex(e["sig"]), body_e)
                except Exception:
                    ok = False
            if not ok:
                bad.append((m["arm"], e["seq"]))
            prev = e["hash"]
    check("memory_chain_and_signatures", not bad, f"{entries} entries, {len(bad)} bad")
    check("memory_no_authority", all(e["grants_authority"] is False and e["executable"] is False
                                     for m in mem for e in m["entries"]))

    failures = []
    for tag, salt in salts.items():
        world = build_world(salt)
        check(f"{tag}_pool", len(world["pool"]) == 150)
        check(f"{tag}_sealed", len(world["sealed"]) == 24)
        for label, veto, shared, oracle, poison, verified in ARMS:
            got = replay(salt, world, veto, shared, oracle, poison, verified)
            exp = rep["arms"][tag][label]
            ok = (got["sealed_curve"] == [{"gen": c["gen"], "solved": c["solved"],
                                           "of": c["of"], "library": c["library"]}
                                          for c in exp["sealed_curve"]]
                  and got["admitted"] == exp["admitted"] and got["poisoned"] == exp["poisoned"]
                  and got["rejected"] == exp["rejected"] and got["stats"] == exp["stats"]
                  and got["rows"] == exp["rows"])
            if not ok:
                failures.append(f"{tag}:{label}")
    check("campaign_replay", not failures, str(failures))

    s1, s2 = rep["arms"]["salt1"], rep["arms"]["salt2"]
    h = rep["hypotheses"]
    checks = [
        ("H1", s1["TRUST"]["sealed_final"] < s1["ORACLE"]["sealed_final"] and
               s2["TRUST"]["sealed_final"] < s2["ORACLE"]["sealed_final"]),
        ("H2", s1["VETO_VALUE"]["sealed_final"] > s1["TRUST"]["sealed_final"] and
               s2["VETO_VALUE"]["sealed_final"] > s2["TRUST"]["sealed_final"]),
        ("H3", s1["VETO_VALUE"]["sealed_final"] >= 0.9 * s1["ORACLE"]["sealed_final"] and
               s2["VETO_VALUE"]["sealed_final"] >= 0.9 * s2["ORACLE"]["sealed_final"]),
        ("H4", s1["VETO_REACH"]["sealed_final"] > s1["TRUST"]["sealed_final"] and
               s2["VETO_REACH"]["sealed_final"] > s2["TRUST"]["sealed_final"] and
               s1["VETO_VALUE"]["sealed_final"] > s1["VETO_REACH"]["sealed_final"] and
               s2["VETO_VALUE"]["sealed_final"] > s2["VETO_REACH"]["sealed_final"]),
        ("H5", s1["VETO_VALUE"]["sealed_final"] > s1["ISOLATED"]["sealed_final"] and
               s2["VETO_VALUE"]["sealed_final"] > s2["ISOLATED"]["sealed_final"]),
        ("H6", s1["VERIFIED_POISON"]["rejected"] >= 1 and s1["VERIFIED_POISON"]["poisoned"] == 0 and
               s2["VERIFIED_POISON"]["rejected"] >= 1 and s2["VERIFIED_POISON"]["poisoned"] == 0 and
               s1["UNVERIFIED"]["poisoned"] >= 1 and s2["UNVERIFIED"]["poisoned"] >= 1 and
               s1["UNVERIFIED"]["sealed_final"] <= s1["VERIFIED_POISON"]["sealed_final"] and
               s2["UNVERIFIED"]["sealed_final"] <= s2["VERIFIED_POISON"]["sealed_final"] and
               (s1["UNVERIFIED"]["sealed_final"] < s1["VERIFIED_POISON"]["sealed_final"] or
                s2["UNVERIFIED"]["sealed_final"] < s2["VERIFIED_POISON"]["sealed_final"])),
    ]
    names = {"H1": "hijack_works", "H2": "value_veto_beats_trust",
             "H3": "value_veto_near_oracle", "H4": "reachability_is_needed",
             "H5": "shared_beats_isolated", "H6": "poison_is_detected"}
    for name, want in checks:
        check(f"hypothesis_{name}", h[f"{name}_{names[name]}"]["verdict"]
              == ("SUPPORTED" if want else "NOT_SUPPORTED"))
    want_verdict = "CURRICULUM_SUPPLY_GOVERNANCE_SUPPORTED" if all(w for _, w in checks) else "NOT_SUPPORTED"
    check("verdict", rep["verdict"] == want_verdict, rep["verdict"])
    print(json.dumps({"checks": "done", "failures": FAIL, "verdict": rep["verdict"]}))
    return 0 if not FAIL else 1


if __name__ == "__main__":
    raise SystemExit(main())
