# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-stale-a2a-agent-card-from-a-revoked-one-during-cross-vendor-task-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-stale-a2a-agent-card-from-a-revoked-one-during-cross-vendor-task-delegation.warrant.json
# Markdown SHA-256:   739f0ccc57181ac501a9ab5f9758879b52141eb3c2cfdb424884548af8b1a3ad
# Code AST SHA-256:   061d4d9ea23f3bad60256ada741616502efcdfe2a590bc65b50f5d7168599fd4
# Verified Classes:   StaleCardDelegationError, CardCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
import urllib.error
import urllib.request
from dataclasses import dataclass, field


class StaleCardDelegationError(RuntimeError):
    """Raised when a task is dispatched against a cached card whose
    authorization state is no longer trustworthy (post-rejection, pre-refetch)."""
    pass


@dataclass
class CardCache:
    card: dict
    fetched_at: float
    admission_rejected: bool = False
    rejected_skills: set = field(default_factory=set)


def fetch_card(url: str, timeout: float = 5.0) -> dict:
    req = urllib.request.Request(url, headers={"Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        import json
        return json.loads(resp.read().decode("utf-8"))


def dispatch_task(cache: CardCache, card_url: str, skill: str, payload: dict) -> dict:
    # Boundary: a prior admission rejection for this (vendor, skill) pair
    # invalidates the cached card until a successful re-fetch occurs.
    if cache.admission_rejected and skill in cache.rejected_skills:
        raise StaleCardDelegationError(
            f"refusing dispatch of skill {skill!r}: cached card for {card_url} "
            f"was admission-rejected at {time.ctime(cache.fetched_at)} and "
            f"has not been re-fetched; card freshness != authorization"
        )

    # Attempt dispatch against the cached card.
    result = _post_task(card_url, skill, payload)

    if result.get("state") == "rejected":
        # Accepted-then-rejected: treat as revocation signal, not task error.
        cache.admission_rejected = True
        cache.rejected_skills.add(skill)
        try:
            fresh = fetch_card(card_url)
        except urllib.error.HTTPError as e:
            if e.code == 404:
                # Hard revocation: evict the pinned card entirely.
                raise StaleCardDelegationError(
                    f"card at {card_url} revoked (404); delegation halted for {skill!r}"
                ) from e
            raise
        # Publication plane may lag admission plane: unchanged card => back off.
        if fresh == cache.card:
            raise StaleCardDelegationError(
                f"card at {card_url} unchanged after admission rejection of "
                f"{skill!r}; publication lagging admission, back off"
            )
        cache.card = fresh
        cache.fetched_at = time.time()
        cache.admission_rejected = False
        cache.rejected_skills.clear()

    return result


def _post_task(card_url: str, skill: str, payload: dict) -> dict:
    # Placeholder for the A2A tasks/sendSubscribe call; returns task state.
    raise NotImplementedError
