# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-late-a2a-push-notification-webhook-as-authoritative-reconciling-stale-task-state-projections-against-the-terminal-state.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-late-a2a-push-notification-webhook-as-authoritative-reconciling-stale-task-state-projections-against-the-terminal-state.warrant.json
# Markdown SHA-256:   8470182e3bb7b1e4a9903e4d7ed59db54774e1ebd0b1d150ca23268af555435c
# Code AST SHA-256:   c7a69ce4b054c2e716071425303e0f07b67b721ad4cb6f73d4a5b3e1261322d7
# Verified Classes:   A2AState, WebhookContractViolation, TaskRecord, WebhookEvent
# 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 A2AState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    AUTH_REQUIRED = "auth-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"
    REJECTED = "rejected"


TERMINAL = {A2AState.COMPLETED, A2AState.FAILED, A2AState.CANCELED, A2AState.REJECTED}

# Reachability in the A2A task lattice. Terminal states have no outbound edges.
REACHABLE = {
    A2AState.SUBMITTED: {A2AState.WORKING, A2AState.REJECTED, A2AState.CANCELED},
    A2AState.WORKING: {
        A2AState.WORKING, A2AState.INPUT_REQUIRED, A2AState.AUTH_REQUIRED,
        A2AState.COMPLETED, A2AState.FAILED, A2AState.CANCELED,
    },
    A2AState.INPUT_REQUIRED: {A2AState.WORKING, A2AState.CANCELED, A2AState.FAILED},
    A2AState.AUTH_REQUIRED: {A2AState.WORKING, A2AState.CANCELED, A2AState.FAILED},
    A2AState.COMPLETED: set(),
    A2AState.FAILED: set(),
    A2AState.CANCELED: set(),
    A2AState.REJECTED: set(),
}


class WebhookContractViolation(RuntimeError):
    """Raised when a webhook cannot be reconciled with the local task lattice
    and synchronous confirmation disagrees or is unavailable."""


@dataclass
class TaskRecord:
    task_id: str
    state: A2AState = A2AState.SUBMITTED
    last_applied_ts: int = 0
    provisional: bool = False
    stale_count: int = 0


@dataclass
class WebhookEvent:
    task_id: str
    event_id: str
    state: A2AState
    timestamp: int


def confirm_via_tasks_get(task_id: str) -> A2AState:
    """Synchronous authoritative read. In production this is an A2A
    `tasks/get` call; here we simulate the remote reducer's settled view."""
    # Placeholder: real implementation issues the RPC and returns the state.
    raise NotImplementedError


def apply_webhook(
    task: TaskRecord,
    event: WebhookEvent,
    seen_event_ids: set,
    confirm=confirm_via_tasks_get,
) -> TaskRecord:
    if event.event_id in seen_event_ids:
        return task  # idempotent redelivery
    seen_event_ids.add(event.event_id)

    # Rule 1: stale or out-of-order by timestamp -> quarantine, never mutate.
    if event.timestamp <= task.last_applied_ts:
        task.stale_count += 1
        return task

    # Rule 2: reachable transition -> apply optimistically.
    if event.state in REACHABLE.get(task.state, set()):
        task.state = event.state
        task.last_applied_ts = event.timestamp
        task.provisional = event.state in TERMINAL
        return task

    # Rule 3: terminal event from non-terminal local state, but not in
    # REACHABLE (e.g. remote skipped a beat). Confirm before committing.
    if event.state in TERMINAL and task.state not in TERMINAL:
        try:
            confirmed = confirm(task.task_id)
        except NotImplementedError:
            raise WebhookContractViolation(
                f"cannot confirm terminal {event.state} for {task.task_id}"
            )
        if confirmed != event.state:
            raise WebhookContractViolation(
                f"webhook claims {event.state} for {task.task_id}, "
                f"tasks/get reports {confirmed}"
            )
        task.state = event.state
        task.last_applied_ts = event.timestamp
        task.provisional = True
        return task

    # Rule 4: unreachable and not confirmable -> escalate, never silently drop.
    # This is the failed-after-completed branch from the trace: dropping it
    # silently reverts a real failure to a false success.
    raise WebhookContractViolation(
        f"illegal transition {task.state}->{event.state} for {task.task_id} "
        f"at ts={event.timestamp}; requires reconciliation"
    )
