# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-v1-0-taskstatusupdateevent-as-terminal-and-why-the-push-notification-webhook-s-final-flag-cannot-be-trusted-to-answ.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-v1-0-taskstatusupdateevent-as-terminal-and-why-the-push-notification-webhook-s-final-flag-cannot-be-trusted-to-answ.warrant.json
# Markdown SHA-256:   d205a2f404d1a6b7678ad76bfbb76cc41a5f53b297594a9fc0a4df98cf3096fa
# Code AST SHA-256:   83862aba54f859de65a538a27d483370b7c2aae65aee02ae3502a6138198c914
# Verified Classes:   TaskLifecycleViolation, HandleState, TaskHandle, TaskRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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

TERMINAL_STATES = {"completed", "canceled", "failed", "rejected"}


class TaskLifecycleViolation(RuntimeError):
    """Raised when a retirement decision violates the A2A terminal-state invariant."""
    pass


class HandleState(Enum):
    ACTIVE = "active"
    TERMINAL_PENDING_CONFIRMATION = "terminal-pending-confirmation"
    RETIRED = "retired"
    AWAITING_CLIENT_INPUT = "awaiting-client-input"
    ORPHANED = "orphaned"


@dataclass
class TaskHandle:
    task_id: str
    state: HandleState = HandleState.ACTIVE
    last_observed_status: Optional[str] = None
    final_flag_seen: bool = False
    confirmed_terminal: bool = False


class TaskRegistry:
    def __init__(self) -> None:
        self._handles: dict[str, TaskHandle] = {}

    def on_webhook(self, task_id: str, status: str, final: bool) -> TaskHandle:
        h = self._handles.setdefault(task_id, TaskHandle(task_id))
        h.last_observed_status = status
        h.final_flag_seen = h.final_flag_seen or final

        if status == "input-required":
            # final:true here describes the stream segment, not the task.
            h.state = HandleState.AWAITING_CLIENT_INPUT
            return h

        if status in TERMINAL_STATES:
            # Do NOT retire on the webhook alone; require GET reconciliation.
            h.state = HandleState.TERMINAL_PENDING_CONFIRMATION
            return h

        h.state = HandleState.ACTIVE
        return h

    def reconcile(self, task_id: str, authoritative_status: str) -> TaskHandle:
        h = self._handles.get(task_id)
        if h is None:
            raise TaskLifecycleViolation(
                f"reconcile called for unknown task {task_id!r}"
            )
        if h.state is not HandleState.TERMINAL_PENDING_CONFIRMATION:
            raise TaskLifecycleViolation(
                f"task {task_id!r} reconciled from state {h.state.value!r}; "
                f"only terminal-pending-confirmation may be retired"
            )
        if authoritative_status not in TERMINAL_STATES:
            # Late correction: the webhook claimed terminal, the task object disagrees.
            h.state = HandleState.ACTIVE
            h.last_observed_status = authoritative_status
            return h
        if authoritative_status != h.last_observed_status:
            raise TaskLifecycleViolation(
                f"terminal-state disagreement for {task_id!r}: "
                f"webhook={h.last_observed_status!r} authoritative={authoritative_status!r}"
            )
        h.confirmed_terminal = True
        h.state = HandleState.RETIRED
        return h

    def retire(self, task_id: str) -> None:
        # Retirement is unreachable except through reconcile().
        h = self._handles.get(task_id)
        if h is None or h.state is not HandleState.RETIRED:
            raise TaskLifecycleViolation(
                f"direct retire() of {task_id!r} forbidden; use reconcile()"
            )


def handle_stream_eof(registry: TaskRegistry, task_id: str) -> TaskHandle:
    h = registry._handles.get(task_id)
    if h is None:
        raise TaskLifecycleViolation(f"stream EOF for untracked task {task_id!r}")
    if h.state is HandleState.ACTIVE and not h.final_flag_seen:
        # EOF without terminal state and without final: orphaned, not failed.
        h.state = HandleState.ORPHANED
        raise TaskLifecycleViolation(
            f"task {task_id!r} reached stream EOF with no terminal state and no "
            f"final flag; classified ORPHANED, requires GET reconciliation"
        )
    return h
