# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-an-a2a-agent-card-after-cross-vendor-task-acceptance-and-why-a-cached-capability-set-silently-invalidates-mid-lifec.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-an-a2a-agent-card-after-cross-vendor-task-acceptance-and-why-a-cached-capability-set-silently-invalidates-mid-lifec.warrant.json
# Markdown SHA-256:   f53f63c06f5afd5d7534993ddeff65afe3df02eebe00fa256fb7d0ce0ecacc03
# Code AST SHA-256:   1627c2df79e2de3f8eb1e16ad244b9ad9c9504565beff6da6168c3467264e603
# Verified Classes:   CapabilityDriftError, AgentCard, Task, Client
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityDriftError(RuntimeError):
    """Raised when an in-flight task's observed behavior diverges from the cached AgentCard."""


@dataclass
class AgentCard:
    fetched_at: float
    declared_ttl: Optional[float]          # None => vendor made no immutability promise
    streaming: bool
    output_modes: frozenset
    signing_key_id: str


@dataclass
class Task:
    task_id: str
    state: str                             # working | completed | failed | canceled
    observed_output_mode: Optional[str] = None
    observed_key_id: Optional[str] = None


@dataclass
class Client:
    card: AgentCard
    pinned_key_id: str
    fetch_card = None                      # callable: () -> AgentCard


def revalidate_before_transition(
    client: Client,
    task: Task,
    transition: str,
    now: Optional[float] = None,
) -> AgentCard:
    """
    Enforce the anomaly-triggered re-validation invariant.
    Returns the (possibly refreshed) card to bind for this transition.
    Raises CapabilityDriftError only when drift is confirmed AND the task
    is not already terminal — never cancel a completed task on a parse failure.
    """
    now = now if now is not None else time.time()
    card = client.card

    ttl_expired = card.declared_ttl is not None and (now - card.fetched_at) > card.declared_ttl
    ttl_absent = card.declared_ttl is None

    anomaly = (
        (transition == "resubscribe" and not card.streaming)
        or (task.observed_output_mode is not None
            and task.observed_output_mode not in card.output_modes)
        or (task.observed_key_id is not None
            and task.observed_key_id != client.pinned_key_id)
    )

    if not (anomaly or (ttl_expired and transition in {"resubscribe", "get-after-gap"})):
        return card

    # Re-fetch and re-bind.
    if client.fetch_card is None:
        raise CapabilityDriftError(
            f"drift detected on task {task.task_id} at {transition}, "
            f"but no card-fetch callable is bound; cannot re-validate"
        )
    fresh = client.fetch_card()
    client.card = fresh
    client.pinned_key_id = fresh.signing_key_id

    # If the peer still cannot honor the transition, classify — do not cancel blindly.
    if transition == "resubscribe" and not fresh.streaming:
        # Fall back to polling; do NOT raise here, this is recoverable.
        return fresh

    if task.observed_output_mode is not None and task.observed_output_mode not in fresh.output_modes:
        raise CapabilityDriftError(
            f"task {task.task_id} emitted outputMode={task.observed_output_mode!r} "
            f"not present in freshly fetched card {sorted(fresh.output_modes)}; "
            f"state={task.state} — reclassify as CapabilityDrift, suppress cancel"
        )

    return fresh


def safe_cancel(client: Client, task: Task, now: Optional[float] = None) -> bool:
    """
    Only cancel a task that is provably non-terminal under the current card.
    A stale-outputModes parse failure must never reach here.
    """
    card = revalidate_before_transition(client, task, transition="get-after-gap", now=now)
    if task.state in {"completed", "failed", "canceled"}:
        # Phantom cancellation guard.
        return False
    if task.observed_output_mode is not None and task.observed_output_mode not in card.output_modes:
        raise CapabilityDriftError(
            f"refusing to cancel {task.task_id}: drift, not failure"
        )
    return True
