# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-agent-card-capability-drift-between-a2a-discovery-and-task-dispatch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-agent-card-capability-drift-between-a2a-discovery-and-task-dispatch.warrant.json
# Markdown SHA-256:   ea991e166833f92d18eecb3a74e294b4ad607b19ef280261f9ab9961e0a0d3b2
# Code AST SHA-256:   9a9e420428577a4f3e511e8ca323a43553196094ff2dbe51645e622f079535cb
# Verified Classes:   CapabilityDriftError, DeliveryMode, AgentCard, AcceptedTask
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CapabilityDriftError(RuntimeError):
    """Raised when a task was accepted under a capability surface that the
    remote no longer honors, and no fallback can safely cover the gap."""


class DeliveryMode(Enum):
    PUSH_BOUND = "push_bound"       # relies solely on webhook
    POLL_FALLBACK = "poll_fallback"  # webhook expected, polling armed
    POLL_ONLY = "poll_only"


@dataclass
class AgentCard:
    push_notifications: bool
    output_modes: frozenset[str]
    skills: frozenset[str]


@dataclass
class AcceptedTask:
    task_id: str
    requested_push: bool
    requested_output_mode: str
    requested_skill: str
    delivery: DeliveryMode = DeliveryMode.PUSH_BOUND
    poll_armed: bool = False


def reconcile_on_acceptance(
    accepted: AcceptedTask,
    live_card: AgentCard,
    allow_poll_fallback: bool,
) -> AcceptedTask:
    """Bind the accepted task to the remote's *post-acceptance* capability
    surface. Discovery-time card is never trusted here."""
    if accepted.requested_skill not in live_card.skills:
        raise CapabilityDriftError(
            f"task {accepted.task_id}: skill {accepted.requested_skill!r} "
            f"absent from live card; cannot honor accepted task"
        )
    if accepted.requested_output_mode not in live_card.output_modes:
        raise CapabilityDriftError(
            f"task {accepted.task_id}: output mode "
            f"{accepted.requested_output_mode!r} dropped by remote"
        )
    push_honored = accepted.requested_push and live_card.push_notifications
    if accepted.requested_push and not push_honored:
        if not allow_poll_fallback:
            raise CapabilityDriftError(
                f"task {accepted.task_id}: requested push but remote "
                f"pushNotifications=false and polling disabled"
            )
        accepted.delivery = DeliveryMode.POLL_FALLBACK
        accepted.poll_armed = True
    elif push_honored:
        accepted.delivery = DeliveryMode.PUSH_BOUND
    else:
        accepted.delivery = DeliveryMode.POLL_ONLY
        accepted.poll_armed = True
    return accepted
