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

Verifies the manifest and every file, the preregistration hash and salt commitment, every signed
memory entry (Ed25519 + SHA-256 chain), and then **re-derives the whole study from the revealed
salts**: the primitives, the generation-0 library and its owners, the 24 targets, presence and
marginal credit, the insider's rejected claim, the generation-1 needs, pools and sealed targets,
every policy's allocation and solved count, every hypothesis and the verdict.

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

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

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

N = 64
PRIMS = 12
AGENTS = ["atlas", "borealis", "cetus", "draco"]
MEM_AGENTS = ["atlas", "borealis", "cetus", "draco", "mallory"]
BUDGET = 24
G0_TASKS = 24
NEED = {"atlas": 11, "borealis": 5, "cetus": 8, "draco": 0}
POOL_DECOYS = {"atlas": 2, "borealis": 2, "cetus": 2, "draco": 8}
POLICIES = ["oracle", "marginal", "uniform", "presence", "claimed", "absent"]
CLAIM_CREDIT = 21
TENANT = "cain42-e461c"
SEED = "e461c"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"

A_PAIRS = [(i, j) for i in (0, 1) for j in range(8)]
B_PAIRS = [(i, j) for i in (2, 3) for j in range(8)]
C_PAIRS = [(i, j) for i in (4, 5) for j in range(8)]
D_DUP = A_PAIRS[0:4] + B_PAIRS[0:3]
D_EXC = [(6, 0), (6, 1)]
G0_SPEC = [
    (("A", 0), ("A", 1)), (("A", 2), ("B", 0)), (("A", 3), ("C", 0)), (("A", 4), ("A", 5)),
    (("A", 6), ("B", 1)), (("A", 7), ("C", 1)),
    (("B", 2), ("A", 8)), (("B", 3), ("B", 4)), (("B", 5), ("C", 2)),
    (("C", 3), ("A", 9)), (("C", 4), ("B", 6)), (("C", 5), ("C", 6)),
    (("C", 7), ("A", 10)), (("C", 8), ("B", 7)), (("C", 9), ("C", 10)),
    (("D", 0), ("A", 11)), (("D", 1), ("B", 8)),
    (("AD", 0), ("A", 12)), (("AD", 1), ("B", 9)), (("AD", 2), ("C", 11)),
    (("AD", 3), ("A", 13)), (("AD", 4), ("B", 10)), (("AD", 5), ("C", 12)), (("AD", 6), ("A", 14)),
]

CH = {"n": 0, "ok": 0, "fail": []}


def check(cond, name):
    CH["n"] += 1
    if cond:
        CH["ok"] += 1
    else:
        CH["fail"].append(name)
    return bool(cond)


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 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 prims(salt):
    out = []
    for k in range(PRIMS):
        r = random.Random(int(sha(canon([salt, "prim", k]))[:16], 16))
        q = list(range(N))
        r.shuffle(q)
        out.append(tuple(q))
    return out


def comp(a, b):
    return tuple(a[b[i]] for i in range(N))


def bkey(beh):
    return sha(bytes(beh))[:16]


def library0(ps):
    owners, beh = {}, {}
    for pair in A_PAIRS:
        b = comp(ps[pair[0]], ps[pair[1]])
        beh[bkey(b)] = b
        owners.setdefault(bkey(b), set()).add("atlas")
    for pair in B_PAIRS:
        b = comp(ps[pair[0]], ps[pair[1]])
        beh[bkey(b)] = b
        owners.setdefault(bkey(b), set()).add("borealis")
    for pair in C_PAIRS:
        b = comp(ps[pair[0]], ps[pair[1]])
        beh[bkey(b)] = b
        owners.setdefault(bkey(b), set()).add("cetus")
    for pair in D_DUP:
        b = comp(ps[pair[0]], ps[pair[1]])
        owners.setdefault(bkey(b), set()).add("draco")
    for pair in D_EXC:
        b = comp(ps[pair[0]], ps[pair[1]])
        beh[bkey(b)] = b
        owners.setdefault(bkey(b), set()).add("draco")
    return owners, beh


def spec_key(spec, ps):
    fam, k = spec
    pair = {"A": A_PAIRS, "B": B_PAIRS, "C": C_PAIRS, "D": D_EXC, "AD": D_DUP}[fam][k]
    return bkey(comp(ps[pair[0]], ps[pair[1]]))


def targets0(ps):
    return [(spec_key(a, ps), spec_key(b, ps)) for a, b in G0_SPEC]


def credit(owners, beh, tasks):
    keys = sorted(beh)
    presence = {a: 0 for a in AGENTS}
    marginal = {a: 0 for a in AGENTS}
    rows = []
    for h1, h2 in tasks:
        target = comp(beh[h1], beh[h2])
        sols = [(k1, k2) for k1 in keys for k2 in keys if comp(beh[k1], beh[k2]) == target]
        present = set()
        for k1, k2 in sols:
            present |= owners[k1] | owners[k2]
        row = {"target": bkey(target), "solutions": len(sols), "present": sorted(present)}
        for a in AGENTS:
            keep = [k for k in keys if owners[k] - {a}]
            still = any(comp(beh[k1], beh[k2]) == target for k1 in keep for k2 in keep)
            row[a] = 0 if still else 1
            marginal[a] += row[a]
        for a in present:
            presence[a] += 1
        rows.append(row)
    return presence, marginal, rows


def new_pairs():
    idx = list(range(7, PRIMS))
    return [(a, b) for a in idx for b in idx]


def gen1(ps, salt):
    pairs = new_pairs()
    r = random.Random(int(sha(canon([salt, "g1"]))[:16], 16))
    r.shuffle(pairs)
    beh, order = {}, []
    for pair in pairs:
        b = comp(ps[pair[0]], ps[pair[1]])
        k = bkey(b)
        if k in beh:
            continue
        beh[k] = b
        order.append(k)
    needed = order[:sum(NEED.values())]
    by_agent, pos = {}, 0
    for a in AGENTS:
        by_agent[a] = needed[pos:pos + NEED[a]]
        pos += NEED[a]
    decoys = []
    for i in range(PRIMS):
        for j in range(PRIMS):
            b = comp(ps[i], ps[j])
            k = bkey(b)
            if k in beh:
                continue
            beh[k] = b
            decoys.append(k)
    r.shuffle(decoys)
    pool, dpos = {}, 0
    for a in AGENTS:
        pool[a] = list(by_agent[a])
        for _ in range(POOL_DECOYS[a]):
            pool[a].append(decoys[dpos])
            dpos += 1
    slots = needed + needed
    r.shuffle(slots)
    tasks = [(slots[i], slots[i + 1]) for i in range(0, len(slots), 2)]
    return beh, needed, pool, tasks


def allocate(shares, budget):
    total = sum(shares.values())
    if total <= 0:
        shares = {a: 1.0 for a in AGENTS}
        total = float(len(AGENTS))
    raw = {a: budget * shares[a] / total for a in AGENTS}
    base = {a: int(raw[a]) for a in AGENTS}
    rem = budget - sum(base.values())
    for a in sorted(AGENTS, key=lambda a: (-(raw[a] - base[a]), a))[:rem]:
        base[a] += 1
    return base


def policy_shares(policy, presence, marginal, claim):
    return {"uniform": {a: 1.0 for a in AGENTS},
            "marginal": {a: float(marginal[a]) for a in AGENTS},
            "presence": {a: float(presence[a]) for a in AGENTS},
            "claimed": {a: float(claim[a]) for a in AGENTS},
            "oracle": {a: float(NEED[a]) for a in AGENTS},
            "absent": {a: 0.0 for a in AGENTS}}[policy]


def pub_of(agent):
    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_chain(rows):
    prev, bad = "", 0
    for e in rows:
        payload = {"seq": e["seq"], "tenant": e["tenant"], "agent": e["agent"], "kind": e["kind"],
                   "key": e["key"], "value": e["value"], "nonce": e["nonce"], "prev": prev,
                   "created_at": e["created_at"], "grants_authority": False, "executable": False}
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub_of(e["agent"]))).verify(
                bytes.fromhex(e["sig"]), canon(payload))
            if sha(prev.encode() + canon(payload) + bytes.fromhex(e["sig"])) != e["hash"]:
                bad += 1
        except Exception:  # noqa: BLE001
            bad += 1
        prev = e["hash"]
    return bad


def main(path):
    B = Path(path)
    man = json.loads((B / "E461C_MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    check(man["schema"] == "cain42.e461c.manifest.v1", "manifest schema")
    check(man["evolution"] == "E461-C", "manifest evolution")
    check(man["status"] == STATUS, "mandatory status line")
    check(man["external_review"] == "NOT_OBTAINED", "external review declared")
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        sig_ok = True
    except Exception:  # noqa: BLE001
        sig_ok = False
    check(sig_ok, "manifest signature")
    files = {n: sha((B / n).read_bytes()) for n in man["files"]}
    check(files == man["files"], "every declared file hash")
    check(merkle([B / n for n in man["files"]]) == man["merkle_root"], "merkle root")
    check((B / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"], "MERKLE_ROOT.txt")

    rep = json.loads((B / "E461C_RUN_REPORT.json").read_text())
    pre = json.loads((B / "E461C_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E461C_PREREGISTRATION_FREEZE.json").read_text())
    salts = json.loads((B / "SALTS.json").read_text())
    check(sha((B / "E461C_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"],
          "preregistration hash")
    check({k: sha(v.encode()) for k, v in salts.items()} == frz["salt_commitments"], "salt commitment")
    check(rep["verdict"] == "COUNTERFACTUAL_CREDIT_SUPPORTED", "verdict")

    totals = 0
    for label in ("salt1", "salt2"):
        salt = salts[label]
        R = rep["salts"][label]
        check(R["salt_commit"] == sha(salt.encode()), f"{label} salt commit")
        ps = prims(salt)
        owners, beh0 = library0(ps)
        t0 = targets0(ps)
        presence, marginal, rows = credit(owners, beh0, t0)
        check(presence == R["presence"], f"{label} presence credit")
        check(marginal == R["marginal"], f"{label} marginal credit")
        check(len(rows) == G0_TASKS, f"{label} task count")
        check([r["target"] for r in rows] == [t["target"] for t in R["tasks0"]], f"{label} task targets")
        check([r["solutions"] for r in rows] == [t["solutions"] for t in R["tasks0"]], f"{label} solution counts")
        for a in AGENTS:
            check([r[a] for r in rows] == [t[a] for t in R["tasks0"]], f"{label} marginal row {a}")

        beh1, needed, pool, targets = gen1(ps, salt)
        check(needed == R["needed"], f"{label} generation-1 needs")
        check(pool == R["pool"], f"{label} candidate pools")
        check([list(x) for x in targets] == [list(x) for x in R["targets1"]], f"{label} sealed targets")
        check(not (set(needed) & set(beh0)), f"{label} gen-1 needs are new")

        claim = {a: 0 for a in AGENTS}
        claim["draco"] = CLAIM_CREDIT
        recomputed = {a: 0 for a in AGENTS}
        for e in R["memory"]["raw"]:
            if e["kind"] == "task0":
                for a in AGENTS:
                    recomputed[a] += int(e["value"]["marginal"][a])
        check(claim == R["claim"], f"{label} insider claim recorded")
        check(recomputed == R["claim_rejected"]["recomputed"], f"{label} claim recomputation")
        check(recomputed != claim and R["claim_rejected"]["rejected"] == 1, f"{label} claim rejected")

        for p in POLICIES:
            shares = policy_shares(p, presence, marginal, claim)
            alloc = allocate(shares, BUDGET) if p != "absent" else {a: 0 for a in AGENTS}
            admitted = {k for a in AGENTS for k in pool[a][:alloc[a]]}
            solved = sum(1 for h1, h2 in targets if h1 in admitted and h2 in admitted)
            A = R["arms"][p]
            check(alloc == A["alloc"], f"{label} {p} allocation")
            check(solved == A["solved"], f"{label} {p} solved")
            check(sum(1 for k in needed if k in admitted) == A["needed_covered"],
                  f"{label} {p} needed coverage")

        rows_m = R["memory"]["raw"]
        check(len(rows_m) == R["memory"]["entries"], f"{label} memory entry count")
        bad = verify_chain(rows_m)
        check(bad == 0 and R["memory"]["bad"] == 0, f"{label} every signature and chain link")
        check(all(e["grants_authority"] is False and e["executable"] is False for e in rows_m),
              f"{label} no entry grants authority")
        check(R["memory"]["duplicate_refused"] == 1, f"{label} duplicate admission refused")
        check(R["memory"]["tenant_probe"]["foreign_visible_to_us"] == 0, f"{label} tenant isolation")
        check(R["memory"]["authority"]["allowed"] is False, f"{label} memory cannot authorize")
        check(R["memory"]["tamper_detected"]["detected"] is True, f"{label} tamper detected")
        check(R["drill"]["distinct_pids"] == 4 and R["drill"]["chain_ok"], f"{label} four-process drill")
        totals += len(rows_m)

    hyp = rep["hypotheses"]
    s1, s2 = rep["salts"]["salt1"], rep["salts"]["salt2"]
    g1 = s1["presence"]["draco"] - s1["marginal"]["draco"]
    g2 = s2["presence"]["draco"] - s2["marginal"]["draco"]
    check(hyp["H1_redundancy_is_not_contribution"]["verdict"] ==
          ("SUPPORTED" if g1 >= 8 and g2 >= 8 and s1["marginal"]["draco"] <= 3
           and s2["marginal"]["draco"] <= 3 else "NOT_SUPPORTED"), "H1 verdict")
    mu = [s["arms"]["marginal"]["solved"] - s["arms"]["uniform"]["solved"] for s in (s1, s2)]
    check(hyp["H2_marginal_beats_uniform"]["verdict"] ==
          ("SUPPORTED" if min(mu) >= 2 else "NOT_SUPPORTED"), "H2 verdict")
    mp = [s["arms"]["marginal"]["solved"] - s["arms"]["presence"]["solved"] for s in (s1, s2)]
    check(hyp["H3_marginal_beats_presence"]["verdict"] ==
          ("SUPPORTED" if min(mp) >= 2 else "NOT_SUPPORTED"), "H3 verdict")
    check(hyp["H4_signed_claim_rejected"]["verdict"] ==
          ("SUPPORTED" if all(s["claim_rejected"]["rejected"] and s["arms"]["claimed"]["solved"] <= 2
                              for s in (s1, s2)) else "NOT_SUPPORTED"), "H4 verdict")
    ledger = all(s["memory"]["chain_ok"] and s["memory"]["bad"] == 0
                 and s["memory"]["duplicate_refused"] == 1
                 and s["memory"]["authority"]["allowed"] is False
                 and s["memory"]["tamper_detected"]["detected"]
                 and s["memory"]["tenant_probe"]["foreign_visible_to_us"] == 0
                 and s["drill"]["distinct_pids"] == 4 and s["drill"]["chain_ok"] for s in (s1, s2))
    check(hyp["H5_ledger_replays_and_grants_nothing"]["verdict"] ==
          ("SUPPORTED" if ledger else "NOT_SUPPORTED"), "H5 verdict")
    repl = all(hyp[k]["verdict"] == "SUPPORTED" for k in
               ("H1_redundancy_is_not_contribution", "H2_marginal_beats_uniform",
                "H3_marginal_beats_presence", "H4_signed_claim_rejected"))
    check(hyp["H6_replication"]["verdict"] == ("SUPPORTED" if repl else "NOT_SUPPORTED"), "H6 verdict")
    check(hyp["H7_external_review"]["verdict"] == "BLOCKED", "H7 external review blocked")
    all_ok = all(hyp[k]["verdict"] == "SUPPORTED" for k in
                 ("H1_redundancy_is_not_contribution", "H2_marginal_beats_uniform",
                  "H3_marginal_beats_presence", "H4_signed_claim_rejected",
                  "H5_ledger_replays_and_grants_nothing", "H6_replication"))
    check(all_ok and rep["verdict"] == "COUNTERFACTUAL_CREDIT_SUPPORTED", "verdict rule")

    check(pre["design"]["budget"] == BUDGET and pre["design"]["agents"] == AGENTS, "preregistration design")
    check(pre["salts_commitment"] == frz["salt_commitments"], "preregistration salts")
    check(json.loads((B / "E461C_DEVIATIONS.json").read_text()).get("deviations") is not None,
          "deviations recorded")

    print(f"{CH['ok']}/{CH['n']} checks")
    for f in CH["fail"]:
        print("FAIL:", f)
    return 0 if CH["ok"] == CH["n"] else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else str(Path(__file__).resolve().parent)))
