# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-an-in-flight-a2a-task-handoff-and-why-does-push-notification-re-registration-silently-orphan-the.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-an-in-flight-a2a-task-handoff-and-why-does-push-notification-re-registration-silently-orphan-the.warrant.json
# Markdown SHA-256:   5072b173b2f55536612a4a9cf4d8e177a416876db1023be9990859d6b5c55762
# Code AST SHA-256:   de812458a5e8f952d8a968fc7625843ceb81fafb75831e4b33d2c69ff07ed309
# Verified Classes:   TaskState, StaleCardDeliveryError, RetentionRaceError, AgentCard, TaskRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TaskState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    UNKNOWN = "unknown"
    LOST = "lost"


class StaleCardDeliveryError(RuntimeError):
    """Raised when a webhook delivery is signed under a card version the
    receiver no longer accepts, and no recovery handshake was offered."""


class RetentionRaceError(RuntimeError):
    """Raised when a reconciliation poll is scheduled outside the receiver's
    advertised task retention window, guaranteeing a false 404."""


@dataclass
class AgentCard:
    version: str
    push_notifications: bool
    task_retention_seconds: int
    signing_key_id: str


@dataclass
class TaskRecord:
    task_id: str
    card_version_at_dispatch: str
    webhook_url: str
    state: TaskState = TaskState.SUBMITTED
    dispatched_at: float = field(default_factory=time.time)
    last_delivery_status: Optional[int] = None


def handle_delivery(
    task: TaskRecord,
    current_card: AgentCard,
    delivery_signature_key_id: str,
    delivery_status: int,
) -> TaskState:
    """Receiver-side handler. Enforces the card-version-consistency invariant:
    a delivery whose signing key is not the current card's key must be
    rejected with 409 + current card, never a bare 401, and must force the
    task into UNKNOWN so the sender polls rather than assuming WORKING."""
    if delivery_signature_key_id != current_card.signing_key_id:
        task.last_delivery_status = 409
        task.state = TaskState.UNKNOWN
        raise StaleCardDeliveryError(
            f"task {task.task_id}: delivery signed under key "
            f"{delivery_signature_key_id!r} but current card "
            f"{current_card.version!r} accepts {current_card.signing_key_id!r}; "
            f"transitioned to UNKNOWN, sender must re-handshake and poll"
        )
    if delivery_status != 200:
        task.last_delivery_status = delivery_status
        task.state = TaskState.UNKNOWN
        raise StaleCardDeliveryError(
            f"task {task.task_id}: delivery rejected with {delivery_status}; "
            f"cannot confirm terminal state"
        )
    task.last_delivery_status = 200
    task.state = TaskState.COMPLETED
    return task.state


def schedule_reconciliation_poll(
    task: TaskRecord, current_card: AgentCard, planned_poll_delay: float
) -> float:
    """Sender-side guard. The poll must land inside the receiver's retention
    window or the 404 will be misread as task loss. Clamp and refuse if the
    card does not advertise a retention bound we can trust."""
    if current_card.task_retention_seconds <= 0:
        raise RetentionRaceError(
            f"task {task.task_id}: card {current_card.version!r} advertises no "
            f"retention bound; cannot schedule a safe reconciliation poll"
        )
    safe_delay = min(planned_poll_delay, current_card.task_retention_seconds * 0.5)
    if planned_poll_delay > current_card.task_retention_seconds:
        raise RetentionRaceError(
            f"task {task.task_id}: planned poll delay {planned_poll_delay}s "
            f"exceeds retention {current_card.task_retention_seconds}s; "
            f"clamping to {safe_delay}s to avoid false 404"
        )
    return safe_delay
