# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-but-cached-agent-card-credential-in-a-cross-org-a2a-trust-chain-when-the-mcp-server-identity-outlives-its-warran.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-but-cached-agent-card-credential-in-a-cross-org-a2a-trust-chain-when-the-mcp-server-identity-outlives-its-warran.warrant.json
# Markdown SHA-256:   c78f66ef195f7dec69a6d3fa26d9c80352806ac264c503ea6128e9eefcf2d45a
# Code AST SHA-256:   146c6349fe6a25d8a50ca5ac992a2ca13b7b719a37e0245429f05ec855ac2e54
# Verified Classes:   WarrantLivenessError, AgentCard, McpServerIdentity, TrustContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class WarrantLivenessError(RuntimeError):
    """Raised when a verified Agent Card does not imply a live delegation warrant."""
    pass


@dataclass
class AgentCard:
    principal: str
    issuer: str
    warrant_ref: str
    warrant_issuer: str
    verified_at: float
    max_staleness_s: float


@dataclass
class McpServerIdentity:
    server_id: str
    host_org: str
    consults_crl_for: set = field(default_factory=set)


@dataclass
class TrustContext:
    card_cache_ttl_s: float = 300.0
    reachable_revocation_issuers: set = field(default_factory=set)
    revoked_warrants: dict = field(default_factory=dict)  # warrant_ref -> revoked_at


def authorize_mcp_call(
    card: AgentCard,
    server: McpServerIdentity,
    ctx: TrustContext,
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    # Card must be fresh enough for the warrant's own staleness budget,
    # not the gateway's generic cache TTL.
    card_age = now - card.verified_at
    if card_age > min(ctx.card_cache_ttl_s, card.max_staleness_s):
        raise WarrantLivenessError(
            f"card for {card.principal} is {card_age:.1f}s old, exceeds "
            f"warrant staleness budget {card.max_staleness_s:.1f}s"
        )

    # The warrant issuer's revocation authority must be reachable from here.
    if card.warrant_issuer not in ctx.reachable_revocation_issuers:
        raise WarrantLivenessError(
            f"warrant issuer {card.warrant_issuer} not in reachable revocation "
            f"bundles; cannot confirm liveness of {card.warrant_ref}"
        )

    # The MCP server must actually consult the warrant issuer's CRL.
    if card.warrant_issuer not in server.consults_crl_for:
        raise WarrantLivenessError(
            f"server {server.server_id} only consults CRLs for "
            f"{sorted(server.consults_crl_for)}; warrant from "
            f"{card.warrant_issuer} is unenforceable at this hop"
        )

    revoked_at = ctx.revoked_warrants.get(card.warrant_ref)
    if revoked_at is not None and revoked_at <= now:
        raise WarrantLivenessError(
            f"warrant {card.warrant_ref} revoked at {revoked_at:.0f}; "
            f"card verification at {card.verified_at:.0f} is stale"
        )

    return True


def handle_a2a_handoff(card, server, ctx):
    # Fail-closed: a verified card that cannot prove warrant liveness is
    # treated as unverified, never as authorized.
    try:
        authorize_mcp_call(card, server, ctx)
    except WarrantLivenessError:
        return {"status": "denied", "reason": "warrant_liveness_unproven"}
    return {"status": "authorized"}
