# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-lifecycle-divergence-at-the-vendor-boundary-the-input-required-working-re-entry-race-and-its-card-de.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-lifecycle-divergence-at-the-vendor-boundary-the-input-required-working-re-entry-race-and-its-card-de.warrant.json
# Markdown SHA-256:   6e6ea7faf1a4924738e31625ab69ef95a0135f7706ce51b20ad6ea59cbfcccf4
# Code AST SHA-256:   5c22d0398634de9a2de69cf09eefc82dc51b52af6f49525be5c1ed3cc678349c
# Verified Classes:   NonMonotonicStateError, TaskState, TaskStatus, MonotonicTaskCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timezone
from enum import IntEnum
from typing import Optional


class NonMonotonicStateError(RuntimeError):
    """Raised when an inbound task state regresses without a newer timestamp."""


class TaskState(IntEnum):
    # Local ordering used only to detect regressions; NOT the A2A wire enum.
    SUBMITTED = 0
    WORKING = 1
    INPUT_REQUIRED = 2
    COMPLETED = 3
    CANCELED = 4
    FAILED = 5


@dataclass(frozen=True)
class TaskStatus:
    state: TaskState
    timestamp: Optional[datetime]  # None == legal-but-unorderable per A2A v1.0
    source: str  # "sync" | "push"


class MonotonicTaskCache:
    """Enforces per-task state monotonicity with channel precedence.

    Invariant: a state may only move forward, OR move backward iff the
    inbound carries a strictly newer timestamp than the cached one.
    Absent timestamps, synchronous replies outrank pushes.
    """

    def __init__(self) -> None:
        self._cache: dict[str, TaskStatus] = {}

    def apply(self, task_id: str, incoming: TaskStatus) -> TaskStatus:
        cached = self._cache.get(task_id)
        if cached is None:
            self._cache[task_id] = incoming
            return incoming

        # Rule 1: timestamped events are ordered by time, regardless of state order.
        if incoming.timestamp is not None and cached.timestamp is not None:
            if incoming.timestamp > cached.timestamp:
                self._cache[task_id] = incoming
                return incoming
            # Older-or-equal timestamp: always discard, even if state is "later".
            return cached

        # Rule 2: untimestamped push within a request window loses to sync.
        if incoming.timestamp is None and cached.source == "sync" and incoming.source == "push":
            return cached

        # Rule 3: untimestamped regression is a divergence -> hard fail, do not apply.
        if incoming.state < cached.state:
            raise NonMonotonicStateError(
                f"task {task_id}: inbound {incoming.state.name} regresses cached "
                f"{cached.state.name} with no newer timestamp (source={incoming.source})"
            )

        # Rule 4: forward or equal untimestamped move is accepted.
        self._cache[task_id] = incoming
        return incoming


def handle_inbound_push(
    cache: MonotonicTaskCache,
    task_id: str,
    wire_state: str,
    timestamp: Optional[datetime],
) -> TaskStatus:
    """Entry point for a push-notification webhook payload."""
    try:
        state = TaskState[wire_state.upper().replace("-", "_")]
    except KeyError as exc:
        raise NonMonotonicStateError(f"unknown A2A TaskState {wire_state!r}") from exc

    incoming = TaskStatus(state=state, timestamp=timestamp, source="push")
    return cache.apply(task_id, incoming)


# --- Reproducing the incident trace -----------------------------------------
if __name__ == "__main__":
    cache = MonotonicTaskCache()
    t0 = datetime(2026, 4, 24, 12, 0, 0, tzinfo=timezone.utc)

    # t1: sync poll -> working
    cache.apply("task-7f2", TaskStatus(TaskState.WORKING, t0, "sync"))
    # t2: sync poll -> input-required
    cache.apply("task-7f2", TaskStatus(TaskState.INPUT_REQUIRED, t0, "sync"))
    # t3: client sends region -> sync reply working
    cache.apply("task-7f2", TaskStatus(TaskState.WORKING, t0, "sync"))
    # t4: stale push re-emits input-required with NO timestamp -> must be discarded,
    #     not treated as a legal re-entry. Without the guard this stalls the task.
    result = handle_inbound_push(cache, "task-7f2", "input-required", timestamp=None)
    assert result.state == TaskState.WORKING, "stale push must not regress state"

    # A genuinely newer timestamped re-entry IS legal and must be accepted.
    t_later = datetime(2026, 4, 24, 12, 0, 5, tzinfo=timezone.utc)
    reentered = handle_inbound_push(cache, "task-7f2", "input-required", timestamp=t_later)
    assert reentered.state == TaskState.INPUT_REQUIRED

    # An untimestamped regression with no sync precedence still raises.
    try:
        cache.apply("task-7f2", TaskStatus(TaskState.WORKING, None, "push"))
    except NonMonotonicStateError as exc:
        print(f"guard fired as designed: {exc}")
