# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-taskstatusupdateevent-as-authoritative-over-its-own-local-task-state-machine-and-when-must-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-taskstatusupdateevent-as-authoritative-over-its-own-local-task-state-machine-and-when-must-it.warrant.json
# Markdown SHA-256:   157246ed361a4b3c045a368c1ffd185648e7d153f9952af915c698f88e3ff508
# Code AST SHA-256:   6fc8b70dd0b98e6e1c642ecad7c3120ac51ac114d2e52789e861e254c87777d6
# Verified Classes:   TaskState, StaleTransitionRefused, StatusEvent, Snapshot, TaskProjection
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime
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"
    REJECTED = "rejected"


TERMINAL = frozenset({
    TaskState.COMPLETED,
    TaskState.FAILED,
    TaskState.CANCELED,
    TaskState.REJECTED,
})


class StaleTransitionRefused(RuntimeError):
    """Raised when a webhook transition would violate the monotonicity invariant."""


@dataclass
class StatusEvent:
    task_id: str
    context_id: str
    state: TaskState
    logical_timestamp: datetime  # event.status.timestamp, NOT delivery time


@dataclass
class Snapshot:
    state: TaskState
    logical_timestamp: datetime


@dataclass
class TaskProjection:
    task_id: str
    context_id: str
    state: TaskState = TaskState.SUBMITTED
    last_snapshot: Optional[Snapshot] = None
    seen_event_ts: datetime = field(default_factory=lambda: datetime.min)

    def apply_webhook(self, event: StatusEvent) -> bool:
        if event.task_id != self.task_id or event.context_id != self.context_id:
            raise StaleTransitionRefused(
                f"task/context mismatch: event=({event.task_id},{event.context_id}) "
                f"projection=({self.task_id},{self.context_id})"
            )

        # Invariant 1: terminal is absorbing.
        if self.state in TERMINAL:
            raise StaleTransitionRefused(
                f"terminal-absorbing violation: projection={self.state.value} "
                f"refuses webhook={event.state.value}"
            )

        # Invariant 2: tasks/get snapshot at T dominates events with transition time < T.
        if self.last_snapshot is not None and \
                event.logical_timestamp < self.last_snapshot.logical_timestamp:
            raise StaleTransitionRefused(
                f"stale event: event_ts={event.logical_timestamp.isoformat()} < "
                f"snapshot_ts={self.last_snapshot.logical_timestamp.isoformat()}"
            )

        # Invariant 3: idempotent replay — same timestamp, same target state is a no-op.
        if event.logical_timestamp == self.seen_event_ts and event.state == self.state:
            return False

        self.state = event.state
        self.seen_event_ts = event.logical_timestamp
        return True

    def apply_snapshot(self, snapshot: Snapshot) -> None:
        if self.last_snapshot is not None and \
                snapshot.logical_timestamp < self.last_snapshot.logical_timestamp:
            raise StaleTransitionRefused(
                "out-of-order tasks/get response; refusing to regress snapshot"
            )
        self.last_snapshot = snapshot
        self.state = snapshot.state


def handle_webhook(projection: TaskProjection, event: StatusEvent) -> str:
    try:
        applied = projection.apply_webhook(event)
    except StaleTransitionRefused as exc:
        # Stale deliveries are reconciliation triggers, not silent drops.
        return f"REFUSED:{exc}; action=tasks/get"
    return "APPLIED" if applied else "NOOP_IDEMPOTENT"


def reconcile(projection: TaskProjection, snapshot: Snapshot) -> None:
    if projection.state in TERMINAL and snapshot.state not in TERMINAL:
        raise StaleTransitionRefused(
            f"authoritative snapshot would regress terminal: "
            f"{projection.state.value} -> {snapshot.state.value}"
        )
    projection.apply_snapshot(snapshot)
