# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-tasks-send-continuation-when-the-remote-agent-card-s-declared-capabilities-streaming-and-the.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-tasks-send-continuation-when-the-remote-agent-card-s-declared-capabilities-streaming-and-the.warrant.json
# Markdown SHA-256:   ccfd26e9c9afc05ea268915447fc2ecffa4c5545c6b5b7ae00dc1cb7a2d73de3
# Code AST SHA-256:   606e8ff16c3ae2bf647b3f2f60e2428c02f96ad0ef179301f87f534ffe9c7180
# Verified Classes:   CapabilityDriftError, CapabilitySnapshot, TaskLedgerEntry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CapabilityDriftError(RuntimeError):
    """Raised when a task continuation would be issued under a capability
    envelope that no longer admits it (A2A v1.0 card/state divergence)."""
    pass


@dataclass(frozen=True)
class CapabilitySnapshot:
    streaming: bool
    push_notifications: bool
    input_modes: frozenset
    output_modes: frozenset


@dataclass
class TaskLedgerEntry:
    task_id: str
    state: str                      # "working", "input-required", "completed", ...
    admitted_under: CapabilitySnapshot
    pending_parts: list = field(default_factory=list)  # media types of queued message parts


def may_continue(entry: TaskLedgerEntry, live: CapabilitySnapshot) -> bool:
    """Return True iff a tasks/send continuation is safe under the live card."""
    if entry.state in ("completed", "failed", "canceled", "unknown"):
        return False
    adm = entry.admitted_under
    # streaming dependency: if we would re-subscribe, live must still stream
    if adm.streaming and not live.streaming:
        return False
    # push dependency
    if adm.push_notifications and not live.push_notifications:
        return False
    # every pending part must be admissible under the live input modes
    for media_type in entry.pending_parts:
        if media_type not in live.input_modes:
            return False
    # output modes the caller still expects must remain declared
    if not adm.output_modes.issubset(live.output_modes):
        return False
    return True


def resume_task(entry: TaskLedgerEntry, live: CapabilitySnapshot) -> str:
    """Decide the resume action; raise on unsafe continuation."""
    if entry.state in ("completed", "failed", "canceled", "unknown"):
        return f"orphan:{entry.task_id}:terminal-or-unknown"
    if not may_continue(entry, live):
        adm = entry.admitted_under
        drift = []
        if adm.streaming and not live.streaming:
            drift.append("streaming:true->false")
        if adm.push_notifications and not live.push_notifications:
            drift.append("pushNotifications:true->false")
        narrowed = [m for m in entry.pending_parts if m not in live.input_modes]
        if narrowed:
            drift.append(f"inputModes narrowed, rejected parts: {narrowed}")
        if not adm.output_modes.issubset(live.output_modes):
            drift.append("outputModes narrowed")
        raise CapabilityDriftError(
            f"refusing tasks/send continuation for {entry.task_id}: "
            f"card drift {drift}; re-negotiate or orphan"
        )
    # safe: downgrade transport if streaming was lost but not required
    transport = "stream" if live.streaming else "poll"
    return f"resume:{entry.task_id}:via:{transport}"
