# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-mutable-lease-rather-than-a-static-capability-manifest-during-cross-vendor-delega.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-mutable-lease-rather-than-a-static-capability-manifest-during-cross-vendor-delega.warrant.json
# Markdown SHA-256:   90e412aeefe41c1fe203e3c68e75c9fbee35095efa64bafc8c53113158839a77
# Code AST SHA-256:   300e2966d94181d9a654a7431aee394b73869b166ac57090b9b8ce2d3ec78d54
# Verified Classes:   CardDriftError, CardLeaseExhaustedError, AgentCard, CardLease
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CardDriftError(RuntimeError):
    """Raised when a task dispatch is rejected in a way that indicates the
    cached Agent Card no longer describes the peer's current contract."""
    pass


class CardLeaseExhaustedError(CardDriftError):
    """Raised when re-resolution fails to produce a card that accepts the
    dispatch, indicating the capability is genuinely retired, not drifted."""
    pass


@dataclass
class AgentCard:
    agent_id: str
    endpoint: str
    skills: set[str]
    input_modes: set[str]
    security_scheme: str
    fetched_at: float
    etag: Optional[str] = None


@dataclass
class CardLease:
    """A card cache entry modeled as a lease with capability-shaped invalidation."""
    card: AgentCard
    contradicted: bool = False
    contradiction_reason: Optional[str] = None
    default_ttl_s: float = 1800.0  # 30 min conservative default for cross-vendor

    def is_stale(self, now: Optional[float] = None) -> bool:
        now = now if now is not None else time.time()
        return self.contradicted or (now - self.card.fetched_at) > self.default_ttl_s

    def mark_contradicted(self, reason: str) -> None:
        self.contradicted = True
        self.contradiction_reason = reason


PROTOCOL_CONCEPTS = ("skill", "input_mode", "output_mode", "security_scheme", "endpoint")


def classify_rejection(status: int, body: dict[str, Any]) -> str:
    """Classify a task-dispatch rejection as capacity vs capability drift."""
    if status in (429, 503):
        return "capacity"
    if status in (404, 410):
        return "capability_drift"
    if status == 400:
        err = str(body.get("error", "")).lower()
        if any(c in err for c in PROTOCOL_CONCEPTS):
            return "capability_drift"
    return "payload_or_domain"


def dispatch_with_lease(
    lease: CardLease,
    skill: str,
    input_mode: str,
    transport,  # callable(endpoint, payload) -> (status, body)
    resolver,   # callable(agent_id) -> AgentCard
    payload: dict[str, Any],
    max_redispatch: int = 2,
) -> dict[str, Any]:
    """Dispatch a task, re-resolving the card on capability-shaped rejection.

    Invariant: card fetch and task dispatch share a version epoch. Any
    capability-shaped rejection invalidates the lease and forces re-resolution
    before the next dispatch. Never mutate the payload to chase a 400 that
    names a protocol concept.
    """
    for attempt in range(max_redispatch + 1):
        if lease.is_stale():
            new_card = resolver(lease.card.agent_id)
            lease.card = new_card
            lease.contradicted = False
            lease.contradiction_reason = None

        if skill not in lease.card.skills:
            raise CardLeaseExhaustedError(
                f"skill {skill!r} not present in re-resolved card for "
                f"{lease.card.agent_id}; capability retired, not drifted"
            )
        if input_mode not in lease.card.input_modes:
            raise CardLeaseExhaustedError(
                f"input_mode {input_mode!r} not accepted by re-resolved card "
                f"for {lease.card.agent_id}; capability narrowed or retired"
            )

        status, body = transport(lease.card.endpoint, {
            "skill": skill,
            "input_mode": input_mode,
            "payload": payload,
            "security_scheme": lease.card.security_scheme,
        })

        if 200 <= status < 300:
            return body

        verdict = classify_rejection(status, body)
        if verdict == "capability_drift":
            lease.mark_contradicted(
                f"status={status} body={body!r} on attempt {attempt}"
            )
            continue  # loop forces re-resolution at top
        if verdict == "capacity":
            raise CardDriftError(
                f"transient capacity rejection ({status}); card is accurate, "
                f"retry with backoff outside this function"
            )
        raise CardDriftError(
            f"payload/domain rejection ({status}) not attributable to card "
            f"drift; do not mutate payload against a stale card: {body!r}"
        )

    raise CardLeaseExhaustedError(
        f"card lease exhausted after {max_redispatch} re-dispatches for "
        f"{lease.card.agent_id}; last contradiction: {lease.contradiction_reason}"
    )
