# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-taskstate-push-notification-as-authoritative-only-after-reconciling-it-against-a-locally-re-fetch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-taskstate-push-notification-as-authoritative-only-after-reconciling-it-against-a-locally-re-fetch.warrant.json
# Markdown SHA-256:   d4eaa3ab38fbef7b101eeb509ef832aa9c9f5c654112f20bfe78133c455e3376
# Code AST SHA-256:   5a7e87fb90eaf44a02e182e5518e6badd93172ab2d35878630abe19e0e6daf12
# Verified Classes:   TaskState, StaleEventRejected, ObligationDropDetected, PushEvent, TaskSnapshot, LocalTask
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    AUTH_REQUIRED = "auth-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


OBLIGATION_STATES = {TaskState.INPUT_REQUIRED, TaskState.AUTH_REQUIRED}
TERMINAL_STATES = {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}


class StaleEventRejected(RuntimeError):
    """Raised when a push event is inconsistent with the re-fetched snapshot."""


class ObligationDropDetected(RuntimeError):
    """Raised when a transition would silently discharge an unmet obligation."""


@dataclass
class PushEvent:
    task_id: str
    event_id: int
    state: TaskState
    timestamp: float
    result_present: bool = False


@dataclass
class TaskSnapshot:
    task_id: str
    state: TaskState
    timestamp: float


@dataclass
class LocalTask:
    task_id: str
    state: TaskState
    obligation_discharged: bool = False
    last_reconcile: float = 0.0
    reconcile_cache: Optional[TaskSnapshot] = None


RECONCILE_WINDOW_S = 5.0


def _needs_reconcile(local: LocalTask, event: PushEvent) -> bool:
    if local.state in OBLIGATION_STATES and event.state not in OBLIGATION_STATES:
        return True  # regressing out of an obligation
    if event.state in OBLIGATION_STATES:
        return True  # creating an obligation
    if event.state in TERMINAL_STATES:
        return True  # terminal events must be confirmed
    return False


def apply_push_event(
    local: LocalTask,
    event: PushEvent,
    fetch_snapshot,  # callable(task_id) -> TaskSnapshot
    now: Optional[float] = None,
) -> LocalTask:
    now = now if now is not None else time.time()

    if _needs_reconcile(local, event):
        if now - local.last_reconcile > RECONCILE_WINDOW_S or local.reconcile_cache is None:
            snapshot = fetch_snapshot(local.task_id)
            local.reconcile_cache = snapshot
            local.last_reconcile = now
        else:
            snapshot = local.reconcile_cache

        # Snapshot is authoritative. If it disagrees with the event, the event
        # is stale or a lagging duplicate and must be dropped.
        if snapshot.state == event.state:
            pass  # consistent; proceed
        elif snapshot.timestamp > event.timestamp:
            # Remote has moved past the event; event is stale.
            raise StaleEventRejected(
                f"event {event.event_id} state={event.state} is stale; "
                f"snapshot state={snapshot.state} ts={snapshot.timestamp} "
                f"> event ts={event.timestamp}"
            )
        else:
            # Snapshot is behind the event; the event may be a leading edge that
            # the snapshot hasn't caught up to. Refuse to apply a terminal or
            # obligation-regressing transition on a lagging snapshot.
            raise StaleEventRejected(
                f"event {event.event_id} state={event.state} leads snapshot "
                f"state={snapshot.state}; refusing to apply without confirmation"
            )

        # Obligation guard: never leave an obligation state unless discharged locally.
        if local.state in OBLIGATION_STATES and event.state not in OBLIGATION_STATES:
            if not local.obligation_discharged:
                raise ObligationDropDetected(
                    f"task {local.task_id}: event {event.event_id} would move "
                    f"{local.state} -> {event.state} without a locally-recorded "
                    f"discharge of the obligation"
                )

        local.state = snapshot.state
        return local

    # Non-obligation, non-terminal, forward transitions: apply idempotently.
    local.state = event.state
    return local
