#!/usr/bin/env python3
"""CCM standalone auditor. No CAIN imports.

Recomputes every world from the revealed salts: candidate behaviours, fixture
matches, sealed tasks; re-verifies every Ed25519 record signature and SHA-256
chain; recomputes every metric, hypothesis and the verdict; checks the manifest.

Usage: python3 verify_ccm_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 Ed25519PrivateKey, Ed25519PublicKey

P, N_CAND, N_USEFUL, N_TASKS = 64, 96, 40, 24
PAIRS = [(i, j) for i in range(16) for j in range(i + 1, 16)][:N_CAND]
ARMS = ("PRIVATE", "NAIVE", "CLAIM", "LEASE")


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


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


def perms(seed: int):
    r = random.Random(seed)
    out = []
    for _ in range(16):
        p = list(range(P))
        r.shuffle(p)
        out.append(tuple(p))
    return out


def fingerprint(ps, ops) -> str:
    x = list(range(P))
    for i in ops:
        x = [ps[i][v] for v in x]
    return sha(bytes(x))


def world(seed: int):
    ps = perms(seed)
    r = random.Random(seed * 7919 + 11)
    useful = set(r.sample(range(N_CAND), N_USEFUL))
    fixtures = {fingerprint(ps, PAIRS[c]): c for c in useful}
    r2 = random.Random(seed * 104729 + 7)
    u = sorted(useful)
    tasks = [r2.sample(u, 2) for _ in range(N_TASKS)]
    return ps, fixtures, tasks


def pubkey(agent: str) -> Ed25519PublicKey:
    seed = hashlib.sha256(("cain-ccm-key:" + agent).encode()).digest()
    return Ed25519PrivateKey.from_private_bytes(seed).public_key()


def verify_chain(rows, ps, fixtures):
    prev = "0" * 64
    seen, useful, fail = set(), set(), None
    for r in rows:
        body = canon({"agent": r["agent"], "cand": r["cand"], "useful": int(r["useful"]), "prev": r["prev"]})
        if sha(body) != r["hash"]:
            fail = fail or f"hash {r['cand']}"
        try:
            pubkey(r["agent"]).verify(bytes.fromhex(r["sig"]), body)
        except Exception:
            fail = fail or f"sig {r['cand']}"
        if r["prev"] != prev:
            fail = fail or f"link {r['cand']}"
        prev = r["hash"]
        seen.add(r["cand"])
        truth = 1 if fingerprint(ps, PAIRS[r["cand"]]) in fixtures else 0
        if int(r["useful"]) != truth:
            fail = fail or f"useful {r['cand']}"
        if truth:
            useful.add(r["cand"])
    return fail, seen, useful


def main() -> int:
    d = Path(sys.argv[1])
    rep = json.loads((d / "CCM_RUN_REPORT.json").read_text())
    pre = json.loads((d / "CCM_PREREGISTRATION.json").read_text())
    checks, fails = [], []

    def ck(name, ok):
        checks.append(name)
        if not ok:
            fails.append(name)

    # salts and seed derivation
    for k, v in rep["salts_revealed"].items():
        ck(f"salt commitment {k}", sha(v.encode()) == pre["salt_commitments"][k] == rep["salt_commitments"][k])
        ck(f"seed {k}", int(sha(v.encode())[:12], 16) == rep["seeds"][k])
    ck("status line", rep["status"] == "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ck("arms", tuple(rep["design"]["arms"]) == ARMS)

    got = {s: {a: {"distinct": [], "duplicates": [], "useful_found": [], "solved": []} for a in ARMS}
           for s in ("salt1", "salt2")}
    for w in rep["worlds"]:
        salt, arm, wi = w["salt"], w["arm"], w["world"]
        base = "LEASE" if arm.startswith("LEASE") else "CLAIM" if arm.startswith("CLAIM") else arm
        ps, fixtures, tasks = world(w["seed"])
        parts = Path(w["path"]).parts
        rows = json.loads((d.joinpath(*parts[parts.index("worlds"):]) / "records.json").read_text())
        if arm == "PRIVATE":
            groups = {}
            for r in rows:
                groups.setdefault(r["agent"], []).append(r)
            seen, useful, fail = set(), set(), None
            for g in groups.values():
                f, s2, u2 = verify_chain(g, ps, fixtures)
                fail = fail or f
                seen |= s2
                useful |= u2
        else:
            fail, seen, useful = verify_chain(rows, ps, fixtures)
        ck(f"chain {salt} {arm} w{wi}", fail is None)
        solved = sum(1 for a, b in tasks if a in useful and b in useful)
        ck(f"records {salt} {arm} w{wi}", len(rows) == w["records"])
        ck(f"distinct {salt} {arm} w{wi}", len(seen) == w["distinct"])
        ck(f"duplicates {salt} {arm} w{wi}", len(rows) - len(seen) == w["duplicates"])
        ck(f"useful {salt} {arm} w{wi}", len(useful) == w["useful_found"])
        ck(f"solved {salt} {arm} w{wi}", solved == w["solved"])
        if arm in ("CLAIM", "LEASE"):
            ck(f"no duplicate candidate {salt} {arm} w{wi}", len(rows) == len(seen))
        if wi < 3 and arm in ARMS:
            for key, val in (("distinct", len(seen)), ("duplicates", len(rows) - len(seen)),
                             ("useful_found", len(useful)), ("solved", solved)):
                got[salt][arm][key].append(val)

    for salt in ("salt1", "salt2"):
        for arm in ARMS:
            for key, vals in got[salt][arm].items():
                ck(f"mean {salt} {arm} {key}", abs(sum(vals) / len(vals) - rep["measurements"][salt][arm][key]) < 1e-9)

    m1, m2 = rep["measurements"]["salt1"], rep["measurements"]["salt2"]
    d1, d2 = rep["drills"]["salt1"], rep["drills"]["salt2"]
    h = {
        "H1": all(m[a]["duplicates"] == 0 for m in (m1, m2) for a in ("CLAIM", "LEASE")),
        "H2": (m1["CLAIM"]["useful_found"] - m1["PRIVATE"]["useful_found"] >= 8 and
               m2["CLAIM"]["useful_found"] - m2["PRIVATE"]["useful_found"] >= 8),
        "H3": (m1["CLAIM"]["solved"] - m1["PRIVATE"]["solved"] >= 4 and
               m2["CLAIM"]["solved"] - m2["PRIVATE"]["solved"] >= 4),
        "H4": (all(dd["LEASE"]["lost_claims"] == 0 and dd["LEASE"]["distinct"] == N_CAND for dd in (d1, d2)) and
               d1["CLAIM"]["lost_claims"] > 0 and d2["CLAIM"]["lost_claims"] > 0),
        "H6": all(m[a]["useful_found"] > m["PRIVATE"]["useful_found"] and
                  m[a]["solved"] > m["PRIVATE"]["solved"]
                  for m in (m1, m2) for a in ("CLAIM", "LEASE")),
    }
    for k, ok in h.items():
        ck(f"{k} recomputed", (rep["hypotheses"][k]["verdict"] == "SUPPORTED") == ok)
    ck("H5 chain and signatures", all(not f.startswith("chain ") for f in fails))
    allok = all(h.values())
    ck("verdict", rep["verdict"] == ("CCM_CLAIMED_MEMORY_SUPPORTED" if allok else "NOT_SUPPORTED"))

    fr = json.loads((d / "CCM_ENGINE_FREEZE.json").read_text())
    ck("preregistration digest", sha((d / "CCM_PREREGISTRATION.json").read_bytes()) == fr["preregistration"])
    ck("report digest", sha((d / "CCM_RUN_REPORT.json").read_bytes()) == fr["report"])
    ck("engine freeze recorded", len(fr["engine"]) >= 5)

    man = json.loads((d / "MANIFEST.json").read_text())
    sig = man.pop("signature")
    Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(sig), canon(man))
    ck("manifest signature", True)
    files = sorted(x for x in d.rglob("*") if x.is_file() and x.name not in {"MANIFEST.json", "MERKLE_ROOT.txt", "SIGNED_BODY.json", "PUBLICATION.json", "CCM_OMEGA_SEAL.json"})
    ck("manifest file set", set(man["files"]) == {str(x.relative_to(d)) for x in files})
    ck("manifest hashes", all(sha((d / f).read_bytes()) == hh for f, hh in man["files"].items()))
    leaves = sorted(sha((d / f).read_bytes()) for f in man["files"])
    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)]
    ck("merkle root", leaves[0] == man["merkle_root"] == (d / "MERKLE_ROOT.txt").read_text().strip())

    bad = [c for c in checks if c in fails]
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    for b in bad:
        print("FAIL", b)
    return 0 if not bad else 1


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