# 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-during-cross-org-a2a-v1-0-delegated-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-but-cached-agent-card-during-cross-org-a2a-v1-0-delegated-handoff.warrant.json
# Markdown SHA-256:   54be1932012f4c5a322f16dc44abf7d796d1e60853bcd37874c77658a2585492
# Code AST SHA-256:   ee7d6c9046323499693c998448b2cfdc8890c95784751efd24668a2ec99c416b
# Verified Classes:   RevokedCapabilityDispatch, AgentCard, CallerPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RevokedCapabilityDispatch(RuntimeError):
    """Raised when a delegated task is about to be dispatched against a
    cached Agent Card whose capability has been revoked by the remote org."""


@dataclass
class AgentCard:
    agent_id: str
    skills: frozenset
    signing_kid: str
    fetched_at: float
    max_age: float                      # seconds, from card hint
    revocation_cadence: Optional[float] # None => remote did not advertise
    signature_valid: bool = True


@dataclass
class CallerPolicy:
    key_revocation_poll_interval: float
    consequential_skills: frozenset
    default_assumed_cadence: float = 300.0  # conservative fallback


def effective_ttl(card: AgentCard, policy: CallerPolicy) -> float:
    """TTL bounded by the *shortest* of card max_age, key-revocation poll
    interval, and the remote's advertised revocation cadence. If the remote
    advertises no cadence, we may not trust a long TTL for consequential work."""
    cadence = card.revocation_cadence
    if cadence is None:
        cadence = policy.default_assumed_cadence
    return min(card.max_age, policy.key_revocation_poll_interval, cadence)


def assert_dispatchable(
    card: AgentCard,
    skill: str,
    policy: CallerPolicy,
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    if not card.signature_valid:
        raise RevokedCapabilityDispatch(
            f"card for {card.agent_id} failed signature verification; "
            f"kid={card.signing_kid} is on the revocation list"
        )

    if skill not in card.skills:
        # Caller-side intent/skill mismatch — caught before dispatch.
        raise RevokedCapabilityDispatch(
            f"skill {skill!r} not present on cached card for {card.agent_id}"
        )

    age = now - card.fetched_at
    ttl = effective_ttl(card, policy)
    if age > ttl:
        raise RevokedCapabilityDispatch(
            f"cached card for {card.agent_id} is {age:.0f}s old, exceeds "
            f"effective TTL {ttl:.0f}s (max_age={card.max_age}, "
            f"cadence={card.revocation_cadence}); re-fetch before dispatch"
        )

    # Consequential skills get the strictest treatment: no caching at all
    # unless the remote advertised a revocation cadence we can bound.
    if skill in policy.consequential_skills and card.revocation_cadence is None:
        raise RevokedCapabilityDispatch(
            f"skill {skill!r} is consequential but remote {card.agent_id} "
            f"advertises no revocation cadence; per-task fetch required"
        )


def dispatch(card: AgentCard, skill: str, payload: dict, policy: CallerPolicy) -> dict:
    assert_dispatchable(card, skill, policy)
    # ... construct A2A tasks/send envelope, sign, transmit ...
    return {"status": "dispatched", "skill": skill, "agent": card.agent_id}
