# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-the-agent-card-task-lifecycle-conformance-gap-in-a2a-v1-0-the-task-status-monotonicity-violation-that-occurs-when-a-p.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-the-agent-card-task-lifecycle-conformance-gap-in-a2a-v1-0-the-task-status-monotonicity-violation-that-occurs-when-a-p.warrant.json
# Markdown SHA-256:   f6e05b7494f50138c3a402c329bda206987c65b3bd9939df678343c3fa6299b9
# Code AST SHA-256:   760a2e3956b2e15b59f1fe397555143cca01b6f7bdcdfa055f0971757f2eb412
# Verified Classes:   TaskState, LifecycleConformanceError, AgentCardSignals, TaskReducer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


TERMINAL = {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}


class LifecycleConformanceError(RuntimeError):
    """Raised when a peer emits a TaskStatusUpdateEvent that violates the
    client's terminal-absorption invariant for an already-absorbed task."""


@dataclass
class AgentCardSignals:
    state_transition_history: bool
    push_notifications: bool
    default_input_modes: bool

    @property
    def eager_absorption_safe(self) -> bool:
        # Absorption is only safe if the peer exposes a recovery channel:
        # either transition history (post-hoc reconcile) or push
        # notifications (out-of-band re-entry). Otherwise a late
        # input-required is unrecoverable and we must defer absorption.
        return self.state_transition_history or self.push_notifications


@dataclass
class TaskReducer:
    card: AgentCardSignals
    grace_seconds: float = 5.0
    absorbed: dict[str, float] = field(default_factory=dict)  # taskId -> absorb_ts
    last_state: dict[str, TaskState] = field(default_factory=dict)

    def _grace_elapsed(self, task_id: str) -> bool:
        ts = self.absorbed.get(task_id)
        return ts is not None and (time.monotonic() - ts) >= self.grace_seconds

    def on_status_update(
        self, task_id: str, new_state: TaskState, final: bool
    ) -> None:
        prev = self.last_state.get(task_id)

        # If the task was provisionally absorbed and the grace window has
        # not elapsed, a regression is recoverable: un-absorb and re-enter.
        if task_id in self.absorbed and not self._grace_elapsed(task_id):
            if new_state == TaskState.INPUT_REQUIRED:
                # Legal only inside the grace window; re-arm a fresh task
                # context rather than merging into the absorbed artifact.
                del self.absorbed[task_id]
                self.last_state[task_id] = new_state
                return

        # Past the grace window, terminal states are absorbing. Any frame
        # for an absorbed task is a lifecycle violation.
        if task_id in self.absorbed and self._grace_elapsed(task_id):
            raise LifecycleConformanceError(
                f"task {task_id!r} received {new_state.value!r} after "
                f"absorption (previous={prev.value if prev else None!r}); "
                f"peer card declares stateTransitionHistory="
                f"{self.card.state_transition_history}, "
                f"pushNotifications={self.card.push_notifications}. "
                f"Client must issue tasks/cancel and route to a new task."
            )

        # Normal forward transition.
        if prev in TERMINAL and new_state not in TERMINAL:
            raise LifecycleConformanceError(
                f"task {task_id!r} regressed {prev.value!r} -> "
                f"{new_state.value!r} without a grace window; "
                f"card signals do not permit eager absorption."
            )

        self.last_state[task_id] = new_state

        if final and new_state in TERMINAL:
            if self.card.eager_absorption_safe:
                self.absorbed[task_id] = time.monotonic() - self.grace_seconds
            else:
                # Defer absorption: hold budget until grace elapses.
                self.absorbed[task_id] = time.monotonic()
