#!/usr/bin/env python3
"""cain-proof-verify: one-command clean-room verification of a CAIN42-PROOF-PACKAGE.

No CAIN imports: needs Python 3.8+, `cryptography`, and the two standalone
verifiers shipped in the package (verifiers/verify_pbft_qc_bundle.py,
verifiers/verify_dag_bundle.py).

    python3 verifiers/cain_proof_verify.py ./CAIN42-PROOF-PACKAGE [--json]

Sections (each VERIFIED or INVALID; the final result is VERIFIED only if every
required section is VERIFIED, INCOMPLETE if a required file is missing):
  MANIFEST       every file's SHA-256 matches; manifest signed by its package key
  MEMBERSHIP     configuration hash recomputed; N=4, f=1, Q=3; fast path declared
  CONSENSUS      every AuthorizationCertificate's quorum certificate verifies for
                 this membership and its bindings re-derive from the committed request
  AUTHORIZATION  every ALLOW was justified: certificate valid, executed call ==
                 authorized action, in scope, same identity, context hash == the
                 consensus-bound hash, unexpired at decision time, first use
  ENFORCEMENT    every DENY is justified by recomputation where it can be; context
                 drift is gate-attested (the gate signs both hashes)
  EXECUTION      every ALLOW has an ExecutionProof referencing it with a VERIFIED
                 postcondition; the sandbox final state equals the allowed calls
  EVIDENCE       the gate's proof chain: every proof re-hashes, is signed by the gate
                 key, and the chain re-folds to the stated head
  DAG            the DAG evidence bundle verifies (verify_dag_bundle.py), if present
"""
from __future__ import annotations

import hashlib
import json
import os
import sys
from pathlib import Path
from typing import Any, Dict, List, Tuple

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import verify_pbft_qc_bundle as Q  # noqa: E402
import verify_dag_bundle as DV  # noqa: E402

h = Q.h
CHAIN_DOMAIN = "CAIN42/MCPGATE/PROOF-CHAIN/v1"


def executed_action(tool: str, args: Dict[str, Any]) -> Dict[str, Any]:
    a = {k: v for k, v in args.items() if not str(k).startswith("_cain_")}
    return {"action": tool, "resource": a.pop("resource", None), "data": a}


def scope_allows(scope: str, action: Dict[str, Any]) -> bool:
    for entry in str(scope).split(","):
        tool, sep, prefix = entry.strip().partition(":")
        if sep and tool == action["action"] and isinstance(action["resource"], str) and action["resource"].startswith(prefix):
            return True
    return False


def verify_package(root: Path) -> Dict[str, Any]:
    sec: Dict[str, Tuple[str, List[str]]] = {}

    def put(name, problems, missing=False):
        sec[name] = ("INCOMPLETE" if missing else ("VERIFIED" if not problems else "INVALID"), problems)

    try:
        man = json.loads((root / "manifest.json").read_text())
    except Exception as e:  # noqa: BLE001
        return {"sections": {"MANIFEST": ("INCOMPLETE", [f"manifest.json unreadable: {e}"])}, "final": "INCOMPLETE"}
    # MANIFEST
    probs = []
    for rel, digest in man.get("files", {}).items():
        p = root / rel
        if not p.is_file():
            probs.append(f"missing {rel}")
        elif hashlib.sha256(p.read_bytes()).hexdigest() != digest:
            probs.append(f"digest mismatch {rel}")
    body = {k: v for k, v in man.items() if k != "manifest_signature_b64"}
    if not Q.ed25519_ok(man.get("package_public_key_b64"), man.get("manifest_signature_b64", ""),
                        hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":")).encode()).hexdigest().encode()):
        probs.append("manifest signature does not verify")
    put("MANIFEST", probs)
    need = ["membership.json", "calls.json", "gate_proofs.json", "sandbox_state.json"]
    have = [f for f in need if (root / f).is_file()]
    if not have and (root / "agents.json").is_file():
        # Agent-only package (Evolution 6): AGENTS is the required section.
        put("AGENTS", verify_agents(json.loads((root / "agents.json").read_text())))
        if (root / "dag_evidence.json").is_file():
            r = DV.verify_bundle(json.loads((root / "dag_evidence.json").read_text()))
            put("DAG", [c["check"] for c in r["checks"] if c["result"] == "FAIL"])
        return _final(sec)
    if len(have) != len(need):
        for n in ("MEMBERSHIP", "CONSENSUS", "AUTHORIZATION", "ENFORCEMENT", "EXECUTION", "EVIDENCE"):
            put(n, ["required file missing"], missing=True)
        return _final(sec)
    mem = json.loads((root / "membership.json").read_text())
    calls = json.loads((root / "calls.json").read_text())
    gp = json.loads((root / "gate_proofs.json").read_text())
    final_state = json.loads((root / "sandbox_state.json").read_text())["final_state"]
    # MEMBERSHIP
    mb = Q.Membership(mem["membership"])
    probs = []
    if (mb.n, mb.f, mb.quorum) != (4, 1, 3):
        probs.append(f"n={mb.n} f={mb.f} q={mb.quorum}")
    if mb.configuration_hash != mem["configuration_hash"]:
        probs.append("configuration hash does not recompute")
    put("MEMBERSHIP", probs)
    # EVIDENCE: gate proof chain
    probs, by_hash = [], {}
    head = h({"domain": CHAIN_DOMAIN, "genesis": gp["gate_id"]})
    for p in gp["proofs"]:
        b = {k: v for k, v in p.items() if k not in ("proof_hash", "gate_signature_b64", "gate_public_key_b64", "chain_head_after")}
        if h(b) != p["proof_hash"]:
            probs.append(f"proof {p['proof_hash'][:12]} does not re-hash")
        if p.get("gate_public_key_b64") != gp["gate_public_key_b64"] or not Q.ed25519_ok(
                gp["gate_public_key_b64"], p["gate_signature_b64"], p["proof_hash"].encode()):
            probs.append(f"proof {p['proof_hash'][:12]} not signed by the gate key")
        head = h({"domain": CHAIN_DOMAIN, "prev": head, "proof": p["proof_hash"]})
        if p.get("chain_head_after") != head:
            probs.append(f"chain breaks at {p['proof_hash'][:12]}")
        by_hash[p["proof_hash"]] = p
    if head != gp["chain_head"]:
        probs.append("chain head does not re-fold")
    put("EVIDENCE", probs)
    # CONSENSUS / AUTHORIZATION / ENFORCEMENT / EXECUTION
    cons, auth, enf, exe = [], [], [], []
    allowed_ids, applied, order = set(), {}, [p["proof_hash"] for p in gp["proofs"]]
    for c in calls:
        proof = by_hash.get(c.get("gate_proof_hash"))
        if proof is None:
            enf.append(f"{c['label']}: no gate proof")
            continue
        act = executed_action(c["tool"], c["arguments"])
        cert = c.get("certificate")
        cert_ok, cert_why = (Q.verify_auth_cert(cert, mb) if isinstance(cert, dict) else (False, "no certificate"))
        if proof["decision"] == "ALLOW":
            b = cert["body"] if isinstance(cert, dict) else {}
            reasons = []
            if not cert_ok:
                reasons.append(f"certificate: {cert_why}")
            if h(act) != b.get("action_hash") or proof["executed_action_hash"] != h(act):
                reasons.append("executed call != authorized action")
            if not scope_allows(b.get("scope", ""), act):
                reasons.append("outside scope")
            if (b.get("identity") or {}).get("client_id") != c["actor"]:
                reasons.append("identity differs")
            if proof["security_context_hash"] != b.get("security_context_hash"):
                reasons.append("context hash differs")
            if b.get("expiration") in (None, "UNBOUND") or float(b["expiration"]) < proof["decided_at"]:
                reasons.append("expired or unbound")
            if b.get("certificate_id") in allowed_ids:
                reasons.append("second use of one authorization")
            allowed_ids.add(b.get("certificate_id"))
            if cert_ok:
                cons.append("ok")
            if reasons:
                auth.append(f"{c['label']}: ALLOW not justified: {reasons}")
            ex = by_hash.get(c.get("execution_proof_hash"))
            if not c.get("forwarded") or ex is None or ex.get("enforcement_proof_hash") != proof["proof_hash"]:
                exe.append(f"{c['label']}: allowed but no execution proof linked to it")
            elif ex.get("postcondition_status") != "VERIFIED":
                exe.append(f"{c['label']}: execution not verified ({ex.get('postcondition_status')})")
            else:
                applied[act["resource"]] = act["data"]
        else:
            code = proof.get("code")
            if c.get("forwarded"):
                enf.append(f"{c['label']}: DENIED but forwarded")
            b = cert["body"] if isinstance(cert, dict) else {}
            justified = {
                "NO_AUTHORIZATION": cert is None,
                "CERTIFICATE_INVALID": isinstance(cert, dict) and not cert_ok,
                "ACTION_SUBSTITUTION": cert_ok and h(act) != b.get("action_hash"),
                "CAPABILITY_EXCEEDED": cert_ok and not scope_allows(b.get("scope", ""), act),
                "IDENTITY_SUBSTITUTION": cert_ok and (b.get("identity") or {}).get("client_id") != c["actor"],
                "SECURITY_CONTEXT_CHANGED": cert_ok and proof.get("authorized_security_context_hash") == b.get("security_context_hash")
                                            and proof.get("execution_security_context_hash") != b.get("security_context_hash"),
                "AUTHORIZATION_REPLAY": cert_ok and b.get("certificate_id") in allowed_ids,
                "AUTHORIZATION_EXPIRED": cert_ok and b.get("expiration") not in (None, "UNBOUND")
                                         and float(b["expiration"]) < proof["decided_at"],
            }.get(code)
            if not justified:
                enf.append(f"{c['label']}: DENY {code} not justified by recomputation")
            if c.get("attack") and c["attack"] != code:
                enf.append(f"{c['label']}: expected {c['attack']}, gate said {code}")
    if applied != final_state:
        exe.append("sandbox final state != the allowed, verified executions")
    put("CONSENSUS", [] if cons else ["no verified consensus authorization"])
    put("AUTHORIZATION", auth)
    put("ENFORCEMENT", enf)
    put("EXECUTION", exe)
    if (root / "agents.json").is_file():
        put("AGENTS", verify_agents(json.loads((root / "agents.json").read_text())))
    if (root / "dag_evidence.json").is_file():
        r = DV.verify_bundle(json.loads((root / "dag_evidence.json").read_text()))
        put("DAG", [c["check"] for c in r["checks"] if c["result"] == "FAIL"])
    return _final(sec)


TRAJ_FIELDS = ("domain", "agent_id", "sequence", "previous_event_hash", "event_type", "epoch", "timestamp",
               "payload_digest", "security_context_hash", "tool_context_hash")


def verify_agents(pkg: Dict[str, Any]) -> List[str]:
    """Evolution 6 sample chains: identity signed by the pinned identity authority;
    trajectory is an intact chain signed by the agent's certified key; for an ALLOW
    the authorization verifies and binds the context, the executed call is a
    TOOL_REQUEST in the trajectory, the gate proof is signed and an execution
    proof links to it; a DENY must not have an execution proof."""
    probs = []
    mb = Q.Membership(pkg["membership"])
    auth = pkg["identity_authority_public_key_b64"]
    for i, s in enumerate(pkg.get("samples", [])):
        tag = f"sample {i} ({s['kind']})"
        for ident in (s["identity"], s["authorized_identity"]):
            body = {k: v for k, v in ident.items() if k not in ("identity_hash", "authority_signature_b64")}
            if h(body) != ident["identity_hash"] or ident.get("authority_public_key_b64") != auth or \
                    not Q.ed25519_ok(auth, ident["authority_signature_b64"], ident["identity_hash"].encode()):
                probs.append(f"{tag}: identity not signed by the pinned identity authority")
        prev = h({"domain": "CAIN42/AGENT/TRAJECTORY-EVENT/v1", "genesis": s["agent"]})
        traj_ok = True
        for j, ev in enumerate(s["trajectory"]):
            if ev["previous_event_hash"] != prev or ev["sequence"] != j or h({k: ev[k] for k in TRAJ_FIELDS}) != ev["event_hash"] \
                    or not Q.ed25519_ok(s["identity"]["agent_public_key_b64"], ev["agent_signature_b64"], ev["event_hash"].encode()):
                traj_ok = False
                break
            prev = ev["event_hash"]
        if s["allowed"]:
            if not traj_ok:
                probs.append(f"{tag}: ALLOW with a broken trajectory")
            ok, why = Q.verify_auth_cert(s["certificate"], mb)
            if not ok:
                probs.append(f"{tag}: authorization: {why}")
            gp, ex = s["gate_proof"], s["execution_proof"]
            if gp["certificate_id"] != s["certificate"]["body"]["certificate_id"] or \
                    gp["security_context_hash"] != s["certificate"]["body"]["security_context_hash"]:
                probs.append(f"{tag}: gate proof does not bind the certificate/context")
            if gp.get("gate_public_key_b64") != pkg["gate_public_key_b64"] or \
                    not Q.ed25519_ok(pkg["gate_public_key_b64"], gp["gate_signature_b64"], gp["proof_hash"].encode()):
                probs.append(f"{tag}: gate proof signature")
            declared = {ev["payload_digest"] for ev in s["trajectory"] if ev["event_type"] == "TOOL_REQUEST"}
            if gp["executed_action_hash"] not in declared:
                probs.append(f"{tag}: executed call not declared in the signed trajectory")
            if not ex or ex.get("enforcement_proof_hash") != gp["proof_hash"]:
                probs.append(f"{tag}: no execution proof linked")
        else:
            if s.get("execution_proof"):
                probs.append(f"{tag}: denied but has an execution proof")
            if s["kind"] == "forged_trajectory" and traj_ok:
                probs.append(f"{tag}: forged-trajectory sample has an intact chain")
    return probs


def _final(sec):
    states = [s for s, _ in sec.values()]
    final = "VERIFIED" if all(s == "VERIFIED" for s in states) else ("INCOMPLETE" if "INCOMPLETE" in states else "INVALID")
    return {"sections": sec, "final": final}


def main(argv: List[str]) -> int:
    if len(argv) < 2:
        print(__doc__)
        return 2
    res = verify_package(Path(argv[1]))
    if "--json" in argv:
        print(json.dumps(res, indent=1))
    else:
        print("CAIN-42 PROOF BUNDLE\n====================\n")
        for name, (state, probs) in res["sections"].items():
            print(f"{name + ':':15s}{state}")
            for p in probs[:5]:
                print(f"    - {p}")
        print(f"\nFINAL RESULT: {res['final']}")
    return 0 if res["final"] == "VERIFIED" else 1


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