# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-push-notification-webhook-has-outlived-its-task-s-terminal-state-and-why-the-agent-card-s-capabilities-pu.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-push-notification-webhook-has-outlived-its-task-s-terminal-state-and-why-the-agent-card-s-capabilities-pu.warrant.json
# Markdown SHA-256:   987183dc88bc542e8f02c9e9169ef1eefa073c0dc7879e086a1b0d9993184105
# Code AST SHA-256:   abada8b61af819e56b888f7aafdb85c0a1c27b36259d0f34cbbd0eacdb851e0e
# Verified Classes:   PushBindingDesyncError, TaskStatusUpdateEvent, ClientTaskLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Literal


class PushBindingDesyncError(RuntimeError):
    """Raised when a push delivery's terminality claims contradict the
    client's latched state or the server-asserted task timestamp."""


TERMINAL_STATES = frozenset({"completed", "failed", "canceled", "rejected"})


@dataclass
class TaskStatusUpdateEvent:
    task_id: str
    state: str
    final: bool
    timestamp: datetime
    artifacts_present: bool = False


@dataclass
class ClientTaskLedger:
    latched_terminal_at: dict[str, datetime] = field(default_factory=dict)
    last_observed_at: dict[str, datetime] = field(default_factory=dict)


def handle_push_delivery(
    event: TaskStatusUpdateEvent,
    ledger: ClientTaskLedger,
    delivery_interval: timedelta = timedelta(seconds=30),
) -> Literal["latch", "ignore", "410"]:
    """Return the correct HTTP disposition for an inbound A2A push event.

    Invariants enforced:
      - Terminal latch requires state in TERMINAL_STATES AND final is True
        AND timestamp is non-decreasing.
      - A delivery for an already-latched task MUST return 410 so the
        remote's push store reaps the binding; returning 2xx extends its
        life to TTL and is a liveness lie.
      - A server-asserted terminal timestamp later than the client latch
        indicates an early latch and MUST raise, not silently pass.
    """
    tid = event.task_id

    if tid in ledger.latched_terminal_at:
        # Binding outlived the client's terminal view. Reap it.
        return "410"

    if event.final and event.state not in TERMINAL_STATES:
        # Mislabeled final flag: do not latch, do not trust.
        raise PushBindingDesyncError(
            f"task {tid}: final=true on non-terminal state={event.state!r}"
        )

    if event.state in TERMINAL_STATES and event.final:
        prev = ledger.last_observed_at.get(tid)
        if prev is not None and event.timestamp < prev:
            raise PushBindingDesyncError(
                f"task {tid}: terminal timestamp {event.timestamp} precedes "
                f"last observed {prev}; server clock or replay divergence"
            )
        if not event.artifacts_present:
            raise PushBindingDesyncError(
                f"task {tid}: terminal state without artifacts; "
                f"likely early-latch from a mislabeled prior event"
            )
        ledger.latched_terminal_at[tid] = event.timestamp
        ledger.last_observed_at[tid] = event.timestamp
        return "latch"

    ledger.last_observed_at[tid] = event.timestamp
    return "ignore"


def reconcile_against_server(
    task_id: str,
    server_terminal_ts: datetime,
    ledger: ClientTaskLedger,
) -> None:
    """Force a tasks/get reconciliation when webhook cadence stalls."""
    latched = ledger.latched_terminal_at.get(task_id)
    if latched is None:
        return
    if server_terminal_ts > latched:
        raise PushBindingDesyncError(
            f"task {task_id}: client latched {latched} but server asserts "
            f"{server_terminal_ts}; client latched early on a non-terminal event"
        )
