# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-agent-card-schema-version-skew-and-the-delegation-warrant-continuity-invariant-in-a2a-v1-0-discovery.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-agent-card-schema-version-skew-and-the-delegation-warrant-continuity-invariant-in-a2a-v1-0-discovery.warrant.json
# Markdown SHA-256:   0cd5b1b7aa5315a723ce35f88dc3124c5801d8183865b74495557dcb0b8d8c0f
# Code AST SHA-256:   6086fe26eeab563f4252481e7c2850954618234d6fce234afc640fe670a49d8a
# Verified Classes:   DelegationWarrantError, AgentCard, TaskEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class DelegationWarrantError(RuntimeError):
    """Raised when a resolved Agent Card cannot warrant a task delegation."""
    pass


@dataclass
class AgentCard:
    protocol_version: str          # e.g. "1.0"
    url: str
    cache_max_age: int             # seconds, from Cache-Control
    streaming: bool
    input_modes: list[str]
    token_url: str
    fetched_at: float              # monotonic seconds


@dataclass
class TaskEnvelope:
    skill: str
    parts_media_types: list[str]
    task_timeout: int              # seconds


def major(version: str) -> int:
    return int(version.split(".")[0])


def assert_warrantable(
    card: AgentCard,
    envelope: TaskEnvelope,
    client_protocol_version: str,
    now: Optional[float] = None,
) -> None:
    """
    Enforce delegation-warrant continuity before dispatching a task.
    Raises DelegationWarrantError on any condition that voids the warrant.
    """
    now = now if now is not None else time.monotonic()

    if major(card.protocol_version) != major(client_protocol_version):
        raise DelegationWarrantError(
            f"protocol major skew: card={card.protocol_version} "
            f"client={client_protocol_version}; capabilities are not "
            f"forward-compatible across majors"
        )

    if card.cache_max_age > envelope.task_timeout:
        # Card lease expires before task could complete; require re-validation.
        raise DelegationWarrantError(
            f"card lease {card.cache_max_age}s exceeds task timeout "
            f"{envelope.task_timeout}s; re-fetch with ETag before dispatch"
        )

    if not set(card.input_modes) & set(envelope.parts_media_types):
        raise DelegationWarrantError(
            f"no exact media-type overlap: card={card.input_modes} "
            f"envelope={envelope.parts_media_types}"
        )

    card_origin = card.url.split("/")[0:3]
    token_origin = card.token_url.split("/")[0:3]
    if card_origin != token_origin:
        raise DelegationWarrantError(
            f"security endpoint origin {token_origin} differs from card "
            f"origin {card_origin}; require re-fetch on 401/403 before retry"
        )


def dispatch(card: AgentCard, envelope: TaskEnvelope, client_version: str) -> str:
    assert_warrantable(card, envelope, client_version)
    # Only after warrant is confirmed may the task transition to 'working'.
    return "working"
