# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capabilities-as-advisory-rather-than-a-warrant-and-re-verify-delegated-task-preconditions.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-agent-card-capabilities-as-advisory-rather-than-a-warrant-and-re-verify-delegated-task-preconditions.warrant.json
# Markdown SHA-256:   d7cf671a8807d3d7adbecbb4ee92b6f3ae117ada282aa8b2e29837ba658b3298
# Code AST SHA-256:   42454cbc9915398c1ecbd4ec91cf6328d8b77426f58b415387bdba572a061d56
# Verified Classes:   CardWarrantExpired, CapabilityMismatch, HandshakeDowngrade, AgentCard, TaskRequest
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class CardWarrantExpired(RuntimeError):
    """Raised when a cached agent card is used past its warrant window."""


class CapabilityMismatch(RuntimeError):
    """Raised when a task's required capability is absent from the live card."""


class HandshakeDowngrade(RuntimeError):
    """Raised when the server silently downgrades a negotiated mode."""


@dataclass
class AgentCard:
    agent_id: str
    fetched_at: float
    ttl: float
    streaming: bool
    push_notifications: bool
    skills: dict            # skill_id -> {"inputModes": [...], "outputModes": [...]}
    extensions: dict        # ext_uri -> {"required": bool}
    signed: bool = False
    kid: Optional[str] = None


@dataclass
class TaskRequest:
    task_id: str
    skill_id: str
    input_mode: str
    requires_streaming: bool
    required_extensions: list = field(default_factory=list)


def admissible(card: AgentCard, task: TaskRequest, now: float) -> bool:
    if card.fetched_at + card.ttl <= now:
        return False
    if task.skill_id not in card.skills:
        return False
    if task.input_mode not in card.skills[task.skill_id]["inputModes"]:
        return False
    if task.requires_streaming and not card.streaming:
        return False
    for ext in task.required_extensions:
        meta = card.extensions.get(ext)
        if meta is None or not meta.get("required", False):
            return False
    if card.signed and not card.kid:
        return False
    return True


def handshake(card: AgentCard, task: TaskRequest, now: float,
              refetch) -> AgentCard:
    # Half-TTL staleness window: re-fetch before delegating.
    if now - card.fetched_at > card.ttl / 2.0:
        card = refetch(card.agent_id)
        if card is None:
            raise CardWarrantExpired(
                f"card for {task.task_id} could not be re-fetched "
                f"within staleness window"
            )

    if not admissible(card, task, now):
        if card.fetched_at + card.ttl <= now:
            raise CardWarrantExpired(
                f"card for {card.agent_id} expired at "
                f"{card.fetched_at + card.ttl:.0f}"
            )
        if task.skill_id not in card.skills:
            raise CapabilityMismatch(
                f"skill {task.skill_id} absent from live card"
            )
        if task.requires_streaming and not card.streaming:
            raise CapabilityMismatch(
                f"task {task.task_id} requires streaming; "
                f"live card says streaming=false"
            )
        for ext in task.required_extensions:
            if ext not in card.extensions:
                raise CapabilityMismatch(
                    f"required extension {ext} absent from live card"
                )
        raise CapabilityMismatch(
            f"task {task.task_id} inadmissible against card {card.agent_id}"
        )

    # Negotiation: send tasks/sendSubscribe, inspect first event.
    first_event = send_subscribe(card, task)
    if task.requires_streaming and first_event.get("type") == "status_update_terminal":
        raise HandshakeDowngrade(
            f"server downgraded streaming for task {task.task_id}; "
            f"first event was terminal status, not a stream chunk"
        )
    return card


def send_subscribe(card: AgentCard, task: TaskRequest) -> dict:
    # Placeholder for the actual A2A transport call.
    return {"type": "status_update_terminal", "task_id": task.task_id}
