#!/usr/bin/env python3
"""Standalone verifier for an OMEGA-SEALed organism run. Imports no CAIN code: stdlib + `cryptography` only.

Checks, from the raw files alone:
  0. every seal carries its assigned OMEGA SEAL number, 1..N with none missing or reused;
  1. every decision record's digest recomputes and its Ed25519 signature verifies (domain cain.fabric.decision-record.v1);
  2. every OMEGA SEAL's signature verifies (domain cain42.omega-seal.v1) and it is bound to its record
     (decision_id, digest, verdict, action path); an authorizing seal records ALLOWED with every stage allow;
  3. every ACCEPTED redemption spends an authorizing seal for exactly that action, at most once;
  4. every effect (compute fit) carries a seal that was redeemed ACCEPTED for exactly that action -- no effect
     without a seal, no seal used for two effects;
  5. every executed self-promotion has an ACCEPTED, authorizing seal;
  6. after the kill switch, no decision authorizes and no effect happens;
  7. the published summary recomputes from these files.
  python3 -I verify_omega_organism.py RUN_DIR [--keys pinned-keys.json]
Exit 0 only if every check passes.
"""
import base64
import hashlib
import json
import sys
from pathlib import Path

REC_DOMAIN, SEAL_DOMAIN = "cain.fabric.decision-record.v1", "cain42.omega-seal.v1"
C = []


def check(name, ok, detail=""):
    C.append(bool(ok))
    print(("PASS " if ok else "FAIL ") + name + (f"  [{detail}]" if detail else ""))


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


def jl(p):
    return [json.loads(x) for x in Path(p).read_text().splitlines() if x.strip()]


def main(argv):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    run = Path(argv[1])
    kp = Path(argv[argv.index("--keys") + 1]) if "--keys" in argv else run / "pinned-keys.json"
    keys = {k: Ed25519PublicKey.from_public_bytes(base64.b64decode(v)) for k, v in json.loads(kp.read_text()).items()}
    dec = jl(run / "decisions.jsonl")
    red = jl(run / "redemptions.jsonl")
    eff = jl(run / "effects.jsonl")
    lin = json.loads((run / "lineage.json").read_text())
    summ = json.loads((run / "summary.json").read_text())

    def sig_ok(key_id, sig_b64, msg):
        try:
            keys[key_id].verify(base64.b64decode(sig_b64), msg)
            return True
        except Exception:
            return False

    rec_bad = seal_bad = bind_bad = auth_bad = 0
    seals = {}
    for i, d in enumerate(dec):
        r, s = d["record"], d["seal"]
        body = {k: v for k, v in r.items() if k not in ("digest", "record_signature", "record_key_id")}
        if hashlib.sha256(canon(body)).hexdigest() != r["digest"] or not sig_ok(
                r["record_key_id"], r["record_signature"], f"{REC_DOMAIN}\x1f{r['digest']}".encode()):
            rec_bad += 1
        sbody = {k: v for k, v in s.items() if k != "signature_b64"}
        if s.get("name") != "OMEGA SEAL" or not sig_ok(s["key_id"], s["signature_b64"],
                                                         f"{SEAL_DOMAIN}\x1f{hashlib.sha256(canon(sbody)).hexdigest()}".encode()):
            seal_bad += 1
        if (s["decision_id"] != r["decision_id"] or s["record_digest"] != r["digest"] or s["verdict"] != r["verdict"]
                or (s.get("action") or {}).get("path") != r["path"] or (s.get("action") or {}).get("service") != r["service"]):
            bind_bad += 1
        if s["authorizes"] and (r["verdict"] != "ALLOWED" or r["blocked"]
                                or any(st["verdict"] != "allow" for st in r["stages"])):
            auth_bad += 1
        seals[s["seal_id"]] = {"i": i, "seal": s, "record": r}
    check("every decision record digest + Ed25519 signature verifies", rec_bad == 0, f"{len(dec)} records, bad={rec_bad}")
    check("every OMEGA SEAL signature verifies", seal_bad == 0, f"{len(dec)} seals, bad={seal_bad}")
    check("every seal is bound to its record (id, digest, verdict, action)", bind_bad == 0, f"bad={bind_bad}")
    check("authorizes=true only for ALLOWED with every stage allow", auth_bad == 0, f"bad={auth_bad}")
    nums = [d["seal"].get("seal_number") for d in dec]
    check("every action has its own assigned OMEGA SEAL number (1..N, none missing, none reused, label matches)",
          nums == list(range(1, len(dec) + 1)) and all(d["seal"].get("seal_label") == f"OMEGA-{d['seal']['seal_number']:09d}" for d in dec),
          f"{len(dec)} numbers, first {dec[0]['seal'].get('seal_label') if dec else None}, last {dec[-1]['seal'].get('seal_label') if dec else None}")

    accepted = {}
    acc_bad = 0
    for x in red:
        if x["result"] != "ACCEPTED":
            continue
        s = seals.get(x["seal_id"])
        if (s is None or not s["seal"]["authorizes"] or s["seal"]["action"]["path"] != x["path"]
                or x["seal_id"] in accepted):
            acc_bad += 1
        accepted[x["seal_id"]] = x
    check("every ACCEPTED redemption spends an authorizing seal for exactly its action, once", acc_bad == 0,
          f"{len(accepted)} accepted, bad={acc_bad}")

    seen, eff_bad = set(), 0
    for e in eff:
        sid = e.get("seal_id")
        a = accepted.get(sid)
        if not sid or a is None or a["path"] != e.get("action_path") or sid in seen \
                or not e.get("action_path", "").startswith(f"fit/{e['task_id']}/") \
                or not e["action_path"].endswith("/" + e["split"]):
            eff_bad += 1
        seen.add(sid)
    check("every effect has its own ACCEPTED seal for exactly that action (no unsealed effect)", eff_bad == 0,
          f"{len(eff)} effects, bad={eff_bad}")

    promo = [r for r in lin["sealed"] if r.get("promoted")]
    p_bad = sum(1 for r in promo if r.get("promote_seal_id") not in accepted
                or not accepted[r["promote_seal_id"]]["path"].startswith("promote/"))
    check("every executed self-promotion has an ACCEPTED authorizing seal", p_bad == 0, f"{len(promo)} promotions, bad={p_bad}")

    kill_i = next((i for i, d in enumerate(dec) for st in d["record"]["stages"]
                   if st["stage"] == "kill_switch" and st["verdict"] == "deny"), None)
    after = dec[kill_i:] if kill_i is not None else []
    after_ids = {d["seal"]["seal_id"] for d in after}
    check("after the kill switch: no authorizing seal, no ACCEPTED redemption, no effect",
          kill_i is not None and not any(d["seal"]["authorizes"] for d in after)
          and not (after_ids & set(accepted)) and not any(e.get("seal_id") in after_ids for e in eff),
          f"{len(after)} sealed NO decisions after kill")

    rc = {}
    for x in red:
        rc[x["result"]] = rc.get(x["result"], 0) + 1
    recompute = {"decisions_sealed": len(dec), "authorizing_seals": sum(d["seal"]["authorizes"] for d in dec),
                 "no_seals": sum(not d["seal"]["authorizes"] for d in dec), "fits_executed_total": len(eff),
                 "fits_with_seal": sum(1 for e in eff if e.get("seal_id")), "promotions_executed": len(promo),
                 "redemptions": rc}
    mism = {k: (summ.get(k), v) for k, v in recompute.items() if summ.get(k) != v}
    check("published summary recomputes from the raw files", not mism, str(mism)[:200])
    check("summary reports 0 effects after kill", summ["kill_switch"]["effects_after_kill"] == 0)
    print(f"{sum(C)}/{len(C)} checks passed")
    return 0 if all(C) else 1


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