#!/usr/bin/env python3
"""Standalone E84 action-receipt verifier — imports no CAIN code.

    python3 verify_action_receipt.py receipt.json --keys trust_keys.json
    python3 verify_action_receipt.py PORTABLE_DIR --keys PORTABLE_DIR/trust_keys.json --require-independent

Exit codes:
   0 VERIFIED_COMPLETE
  10 VERIFIED_WITH_UNVERIFIED_EFFECT
  20 VERIFIED_AUTHORIZATION_ONLY / VERIFIED_EXECUTION_ONLY
  30 INCOMPLETE_EVIDENCE
  40 INVALID_SIGNATURE
  41 INVALID_BINDING
  42 INVALID_PROOF
  43 REPLAY_DETECTED
  44 TRUST_POLICY_FAILURE

Only exit 0 is a complete claim. Nothing here says an external event happened;
it says the evidence package is internally consistent under the pinned keys.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

D_RECEIPT = "CAIN42/E84/ACTION-RECEIPT/v1"
D_ACTION = "CAIN42/ACTION-COMMIT/CANONICAL-ACTION/v1"
D_AUTH = "CAIN42/E84/AUTHORIZATION/v1"
D_GRANT = "CAIN42/E84/SINGLE-USE-GRANT/v1"
D_ENFORCE = "CAIN42/E84/ENFORCEMENT/v1"
D_EXEC = "CAIN42/E84/EXECUTION/v1"
D_EFFECT = "CAIN42/E84/EFFECT/v1"
D_CHECKPOINT = "CAIN42/E84/LOG-CHECKPOINT/v1"
D_COSIGN = "CAIN42/E84/WITNESS-COSIGNATURE/v1"
D_DELEGATION = "cain61.delegation.v1"
D_POLICY = "CAIN42/ACTION-COMMIT/POLICY-SET/v1"
SCHEMA = "cain.receipt.v1"

class V:
    def __init__(self):
        self.checks: List[Tuple[str, bool, str]] = []
        self.errors: List[str] = []
        self.warnings: List[str] = []

    def check(self, name: str, ok: bool, detail: str = "", kind: Optional[str] = None) -> bool:
        self.checks.append((name, bool(ok), detail))
        if not ok and kind and kind not in self.errors:
            self.errors.append(kind)
        return bool(ok)


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


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


def digest(domain: str, fields: Dict[str, Any]) -> str:
    return sha_hex(canon({"domain": domain, **fields}))


def e84_verify(pub_b64: str, sig_b64: str, domain: str, fields: Dict[str, Any]) -> bool:
    try:
        from cryptography.exceptions import InvalidSignature
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(base64.b64decode(pub_b64)).verify(
            base64.b64decode(sig_b64), digest(domain, fields).encode())
        return True
    except Exception:
        return False


def e61_canon(o: Any) -> bytes:
    # E61 normalizes integral floats before canonical JSON.
    def norm(x):
        if isinstance(x, float):
            if not __import__("math").isfinite(x):
                raise ValueError("NON_FINITE")
            return int(x) if x.is_integer() else x
        if isinstance(x, dict):
            return {str(k): norm(v) for k, v in x.items()}
        if isinstance(x, (list, tuple)):
            return [norm(v) for v in x]
        return x
    return json.dumps(norm(o), sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def e61_verify(pub_b64: str, sig_b64: str, domain: str, body: Dict[str, Any]) -> bool:
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(base64.b64decode(pub_b64)).verify(
            base64.b64decode(sig_b64), domain.encode() + b"\0" + e61_canon(body))
        return True
    except Exception:
        return False


def leaf_hash(data: bytes) -> bytes:
    return hashlib.sha256(b"\x00" + data).digest()


def node_hash(l: bytes, r: bytes) -> bytes:
    return hashlib.sha256(b"\x01" + l + r).digest()


def verify_inclusion(index: int, size: int, leaf: bytes, root_b64: str, proof: Sequence[str]) -> bool:
    if size <= 0 or not 0 <= index < size:
        return False
    fn, sn, r = index, size - 1, leaf
    for p in proof:
        c = base64.b64decode(p)
        if sn == 0:
            return False
        if fn & 1 or fn == sn:
            r = node_hash(c, r)
            while fn and not (fn & 1):
                fn >>= 1
                sn >>= 1
        else:
            r = node_hash(r, c)
        fn >>= 1
        sn >>= 1
    return sn == 0 and base64.b64encode(r).decode() == root_b64


def load(path: Path) -> Tuple[dict, Optional[Path]]:
    if path.is_dir():
        files = list(path.glob("receipt*.json"))
        if not files:
            raise SystemExit(f"no receipt*.json in {path}")
        return json.loads(files[0].read_text()), path
    return json.loads(path.read_text()), None


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("receipt")
    ap.add_argument("--keys", help="JSON {role: base64 pubkey}; required for a complete claim")
    ap.add_argument("--allow-embedded", action="store_true", help="use signer_pub fields (not a pinned trust policy)")
    ap.add_argument("--require-independent", action="store_true",
                    help="fail unless a cosignature is classified INDEPENDENT")
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()

    path = Path(a.receipt)
    rec, pkg = load(path)
    body = rec.get("body") or {}
    v = V()
    keys: Dict[str, str] = {}
    if a.keys:
        keys = json.loads(Path(a.keys).read_text())

    def pin(role: str, embedded: str) -> bool:
        if role in keys:
            return keys[role] == embedded
        return a.allow_embedded

    # ---------------------------------------------------------------- schema
    v.check("schema_is_cain_receipt_v1", body.get("schema") == SCHEMA, str(body.get("schema")), "BINDING")
    required = ("receipt", "principal", "agent", "delegation", "action", "authorization",
                "enforcement", "execution", "effect", "log")
    missing = [k for k in required if not body.get(k)]
    v.check("required_sections_present", not missing, ",".join(missing), "MISSING")

    receipt = body.get("receipt") or {}
    tenant = receipt.get("tenant", "")
    v.check("receipt_has_tenant_action_id", bool(tenant) and bool(receipt.get("action_id")), tenant, "MISSING")

    # ---------------------------------------------------------------- action digest
    action = body.get("action") or {}
    ad = digest(D_ACTION, action.get("normalized") or {})
    v.check("action_digest_recomputed", ad == action.get("digest"), f"{ad[:16]}… vs {str(action.get('digest'))[:16]}…",
            "BINDING")
    v.check("action_tenant_matches_receipt", (action.get("normalized") or {}).get("tenant") == tenant, "", "BINDING")
    v.check("arguments_digest_recomputed",
            action.get("arguments_digest") == digest("CAIN42/E84/ACTION-ARGUMENTS/v1",
                                                     {"args": (action.get("normalized") or {}).get("normalized_arguments") or {}}),
            "", "BINDING")

    # ---------------------------------------------------------------- principal / agent / tenant isolation
    v.check("principal_present", bool((body.get("principal") or {}).get("id")), "", "MISSING")
    agent = body.get("agent") or {}
    v.check("agent_present", bool(agent.get("id")) and bool(agent.get("pub")), agent.get("id", ""), "MISSING")
    for name in ("authorization", "enforcement", "execution", "effect"):
        sec = body.get(name) or {}
        b = sec.get("body") if "body" in sec else sec
        v.check(f"{name}_tenant_matches", (b or {}).get("tenant") in ("", tenant), str((b or {}).get("tenant")), "BINDING")

    # ---------------------------------------------------------------- receipt signature
    v.check("receipt_digest_recomputed", rec.get("digest") == digest(D_RECEIPT, body), "", "BINDING")
    v.check("receipt_signer_is_pinned_issuer", pin("issuer", rec.get("signer_pub", "")), rec.get("signer_pub", "")[:16],
            "TRUST")
    v.check("receipt_signature_valid",
            e84_verify(rec.get("signer_pub", ""), rec.get("signature_b64", ""), D_RECEIPT, body), "", "SIGNATURE")

    # ---------------------------------------------------------------- authorization
    auth = body.get("authorization") or {}
    ab = auth.get("body") or auth
    v.check("authorization_decision_allow", ab.get("decision") == "ALLOW", str(ab.get("decision")), "BINDING")
    v.check("authorization_bound_to_action", ab.get("action_digest") == ad, "", "BINDING")
    v.check("authorization_policy_present", bool(ab.get("policy_id")) and bool(ab.get("policy_version"))
            and bool(ab.get("policy_digest")), str(ab.get("policy_id")), "MISSING")
    v.check("authorization_not_expired_at_decision",
            float(ab.get("expires_at") or 0) > float(ab.get("decided_at") or 0), "", "BINDING")
    v.check("policy_digest_recomputed",
            ab.get("policy_digest") == digest(D_POLICY, ab.get("policy_body") or {}), "", "BINDING")
    v.check("policy_version_matches_body",
            ab.get("policy_version") == (ab.get("policy_body") or {}).get("version"), "", "BINDING")
    v.check("authorization_signer_is_pinned", pin("authorizer", auth.get("signer_pub", "")), "", "TRUST")
    v.check("authorization_signature_valid",
            e84_verify(auth.get("signer_pub", ""), auth.get("signature_b64", ""), D_AUTH, ab), "", "SIGNATURE")
    grant = ab.get("grant") or {}
    gb = grant.get("body") or {}
    v.check("grant_digest_recomputed", grant.get("digest") == digest(D_GRANT, gb), "", "BINDING")
    v.check("grant_signature_valid",
            e84_verify(grant.get("signer_pub", ""), grant.get("signature_b64", ""), D_GRANT, gb), "", "SIGNATURE")
    v.check("grant_bound_to_action", gb.get("action_digest") == ad and gb.get("tenant") == tenant, "", "BINDING")
    v.check("grant_is_single_use", int(gb.get("max_uses", 0)) == 1, str(gb.get("max_uses")), "BINDING")
    v.check("grant_nonce_present", bool(gb.get("nonce")), "", "MISSING")

    # ---------------------------------------------------------------- enforcement
    enf = body.get("enforcement") or {}
    eb = enf.get("body") or {}
    v.check("enforcement_decision_allow", eb.get("decision") == "ALLOW", str(eb.get("decision")), "BINDING")
    v.check("enforcement_bound_to_action", eb.get("action_digest") == ad, "", "BINDING")
    v.check("enforcement_resource_matches", eb.get("resource") == (action.get("target") or {}).get("resource"), "", "BINDING")
    v.check("enforcement_nonce_matches_grant", eb.get("nonce") == gb.get("nonce") and bool(eb.get("nonce")), "", "REPLAY")
    v.check("enforcement_signer_is_pinned", pin("enforcement", enf.get("signer_pub", "")), "", "TRUST")
    v.check("enforcement_signature_valid",
            e84_verify(enf.get("signer_pub", ""), enf.get("signature_b64", ""), D_ENFORCE, eb), "", "SIGNATURE")

    # ---------------------------------------------------------------- execution
    exe = body.get("execution") or {}
    xb = exe.get("body") or {}
    v.check("execution_bound_to_action", xb.get("action_digest") == ad, "", "BINDING")
    v.check("execution_idempotency_matches",
            xb.get("idempotency_key") in ("", receipt.get("idempotency_key")), "", "BINDING")
    v.check("execution_completed_after_start",
            float(xb.get("completed_at") or 0) >= float(xb.get("started_at") or 0), "", "BINDING")
    v.check("execution_status_present", bool(xb.get("status")), str(xb.get("status")), "MISSING")
    if str(xb.get("status")).upper() in ("SUCCESS", "OK", "COMMITTED"):
        v.check("execution_has_output_digest", bool(xb.get("output_digest")), "", "MISSING")
    v.check("executor_signer_is_pinned", pin("executor", exe.get("signer_pub", "")), "", "TRUST")
    v.check("execution_signature_valid",
            e84_verify(exe.get("signer_pub", ""), exe.get("signature_b64", ""), D_EXEC, xb), "", "SIGNATURE")

    # ---------------------------------------------------------------- effect
    eff = body.get("effect") or {}
    fb = eff.get("body") or {}
    state = str(fb.get("state") or "").upper()
    v.check("effect_state_is_known", state in ("EFFECT_VERIFIED", "EFFECT_UNVERIFIED", "EFFECT_UNKNOWN",
                                               "EFFECT_CONTRADICTED", "NO_EFFECT"), state, "BINDING")
    if state == "EFFECT_VERIFIED":
        v.check("effect_is_authoritative", bool(fb.get("authoritative")), "", "BINDING")
        v.check("effect_has_observation_digest", bool(fb.get("observation_digest")), "", "MISSING")
    v.check("effect_resource_matches", fb.get("resource") == (action.get("target") or {}).get("resource"), "", "BINDING")
    v.check("effect_record_matches_action",
            fb.get("record_id") == ((action.get("normalized") or {}).get("normalized_arguments") or {}).get("id"),
            "", "BINDING")
    v.check("execution_provider_matches_resource", xb.get("provider_ref") == fb.get("resource"), "", "BINDING")
    v.check("execution_and_effect_do_not_contradict",
            not (str(xb.get("status")).upper() in ("SUCCESS", "OK", "COMMITTED")
                 and str(fb.get("state")).upper() == "EFFECT_CONTRADICTED"), "", "BINDING")
    if str(xb.get("status")).upper() in ("SUCCESS", "OK", "COMMITTED") and state == "EFFECT_VERIFIED":
        v.check("execution_output_matches_effect", xb.get("output_digest") == fb.get("observation_digest"), "", "BINDING")
    v.check("effect_signer_is_pinned", pin("resource", eff.get("signer_pub", "")), "", "TRUST")
    v.check("effect_signature_valid",
            e84_verify(eff.get("signer_pub", ""), eff.get("signature_b64", ""), D_EFFECT, fb), "", "SIGNATURE")

    # ---------------------------------------------------------------- delegation
    dele = body.get("delegation") or {}
    chain = dele.get("chain") or []
    root = dele.get("root") or {}
    revoked = set(dele.get("revoked") or [])
    v.check("delegation_chain_present", bool(chain), str(len(chain)), "MISSING")
    parent_agent = root.get("agent", "")
    parent_scope = set(root.get("scope") or [])
    parent_res = set(root.get("resources") or [])
    parent_exp = float(root.get("expires_at") or 0)
    ok_chain = True
    for i, g in enumerate(chain):
        gb2 = {k: x for k, x in g.items() if k != "signature_b64"}
        signer = g.get("signer_pub", "")
        ok_chain &= pin(f"agent:{g.get('parent_agent')}", signer)
        ok_chain &= e61_verify(signer, g.get("signature_b64", ""), D_DELEGATION, gb2)
        ok_chain &= g.get("parent_agent") == parent_agent and g.get("child_agent") and int(g.get("depth", 0)) == i + 1
        ok_chain &= g.get("grant_id") not in revoked
        ok_chain &= float(g.get("expires_at") or 0) <= parent_exp
        ok_chain &= set(g.get("scope") or []).issubset(parent_scope)
        ok_chain &= set(g.get("resources") or []).issubset(parent_res)
        ok_chain &= g.get("audience") == tenant
        if i > 0:
            ok_chain &= g.get("parent_grant_id") == chain[i - 1].get("grant_id")
        parent_agent = g.get("child_agent")
        parent_scope = set(g.get("scope") or [])
        parent_res = set(g.get("resources") or [])
        parent_exp = float(g.get("expires_at") or 0)
    v.check("delegation_signatures_and_attenuation", ok_chain, "", "SIGNATURE")
    v.check("delegation_child_is_the_action_agent", parent_agent == agent.get("id"), parent_agent, "BINDING")

    # ---------------------------------------------------------------- log + checkpoint
    log = body.get("log") or {}
    core = {k: x for k, x in body.items() if k != "log"}
    core_digest = digest(D_RECEIPT, {"core": core, "version": 1})
    v.check("leaf_data_is_the_core_digest", log.get("leaf_data_digest") == core_digest, "", "BINDING")
    size = int(log.get("tree_size") or 0)
    idx = int(log.get("leaf_index") or 0)
    root_b64 = log.get("tree_root_b64") or ""
    leaf = leaf_hash(bytes.fromhex(core_digest))
    v.check("merkle_inclusion_valid",
            verify_inclusion(idx, size, leaf, root_b64, log.get("inclusion_proof") or []), f"idx={idx} size={size}",
            "PROOF")
    cp = log.get("checkpoint") or {}
    cb = cp.get("body") or {}
    v.check("checkpoint_matches_tree", cb.get("origin") == log.get("origin") and int(cb.get("size") or -1) == size
            and cb.get("root_b64") == root_b64, "", "PROOF")
    v.check("checkpoint_signer_is_pinned", pin("log", cp.get("signer_pub", "")), "", "TRUST")
    v.check("checkpoint_signature_valid",
            e84_verify(cp.get("signer_pub", ""), cp.get("signature_b64", ""), D_CHECKPOINT, cb), "", "PROOF")
    cosigs = cp.get("cosignatures") or []
    good_cos, independent = 0, 0
    for c in cosigs:
        cbb = c.get("body") or {}
        ok = (pin("witness", c.get("signer_pub", ""))
              and e84_verify(c.get("signer_pub", ""), c.get("signature_b64", ""), D_COSIGN, cbb)
              and int(cbb.get("size") or -1) == size and cbb.get("root_b64") == root_b64)
        good_cos += 1 if ok else 0
        if ok and str(cbb.get("classification", "")).upper() == "INDEPENDENT":
            independent += 1
        elif ok:
            v.warnings.append(f"witness {cbb.get('witness')} classification={cbb.get('classification')}")
    v.check("cosignatures_valid", all(
        pin("witness", c.get("signer_pub", "")) and e84_verify(c.get("signer_pub", ""),
                                                               c.get("signature_b64", ""), D_COSIGN, c.get("body") or {})
        for c in cosigs), f"{good_cos}/{len(cosigs)}", "SIGNATURE")
    declared = str((body.get("verification") or {}).get("witness_classification") or "NONE")
    if declared != "NONE":
        v.check("declared_witness_has_a_valid_cosignature", good_cos >= 1, f"{good_cos} valid", "PROOF")
    if a.require_independent:
        v.check("independent_witness_required", independent >= 1, f"{independent} independent", "TRUST")
    v.check("witness_classification_not_overstated",
            (body.get("verification") or {}).get("witness_classification") in
            (None, "NONE", "SIMULATED_LOCAL", "SAME_ORG", "DIFFERENT_PROVIDER", "INDEPENDENT"),
            str((body.get("verification") or {}).get("witness_classification")), "BINDING")

    # ---------------------------------------------------------------- result class
    if "TRUST" in v.errors:
        result, code = "TRUST_POLICY_FAILURE", 44
    elif "SIGNATURE" in v.errors:
        result, code = "INVALID_SIGNATURE", 40
    elif "PROOF" in v.errors:
        result, code = "INVALID_PROOF", 42
    elif "REPLAY" in v.errors:
        result, code = "REPLAY_DETECTED", 43
    elif "BINDING" in v.errors:
        result, code = "INVALID_BINDING", 41
    elif "MISSING" in v.errors:
        result, code = "INCOMPLETE_EVIDENCE", 30
    elif state != "EFFECT_VERIFIED":
        result, code = "VERIFIED_WITH_UNVERIFIED_EFFECT", 10
    else:
        result, code = "VERIFIED_COMPLETE", 0

    out = {"result": result, "exit_code": code, "receipt_id": rec.get("receipt_id"),
           "tenant": tenant, "action_digest": ad, "effect_state": state,
           "witness_cosignatures": good_cos, "independent_cosignatures": independent,
           "checks": [{"check": n, "ok": o, "detail": d} for n, o, d in v.checks],
           "errors": v.errors, "warnings": v.warnings,
           "verifier": "E84 verify_action_receipt v1 (no CAIN imports)"}
    if a.json:
        print(json.dumps(out, indent=1))
    else:
        for n, o, d in v.checks:
            print(f"{'PASS' if o else 'FAIL'} {n}" + (f"  ({d})" if d else ""))
        print(f"\n{result}  (exit {code})  effect={state}  witnesses={good_cos} independent={independent}")
    return code


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