# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a2a-push-notification-webhooks-as-replayable-event-logs-rather-than-one-shot-rpc-callbacks.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a2a-push-notification-webhooks-as-replayable-event-logs-rather-than-one-shot-rpc-callbacks.warrant.json
# Markdown SHA-256:   bfb9ecc6ddd87d7276d90fa4851de26202d062457adcc7fd97904dc02491b5e9
# Code AST SHA-256:   bdf91292a63efecdfb05f6d6f60f6a0528af73dd7c359aa78718a64e60c3e6a6
# Verified Classes:   NonMonotonicWebhookError, StateRank, TaskState, WebhookFold
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Optional


class NonMonotonicWebhookError(RuntimeError):
    """Raised when a webhook's seq advances but its rank regresses the task state."""
    pass


class StateRank(IntEnum):
    PENDING = 0
    WORKING = 1
    COMPLETED = 2
    FAILED = 2
    CANCELED = 2


@dataclass
class TaskState:
    task_id: str
    rank: StateRank = StateRank.PENDING
    last_applied_seq: int = -1
    artifact: Optional[str] = None
    needs_reconciliation: bool = False
    seen_side_effect_keys: set = field(default_factory=set)


class WebhookFold:
    """Monotonic fold of A2A push-notification webhooks into task state."""

    def __init__(self) -> None:
        self._tasks: Dict[str, TaskState] = {}

    def apply(self, task_id: str, seq: int, rank: StateRank,
              artifact: Optional[str] = None) -> TaskState:
        st = self._tasks.setdefault(task_id, TaskState(task_id=task_id))

        # Replay: already applied or older. Drop entirely.
        if seq <= st.last_applied_seq:
            return st

        # Gap detection: a webhook was lost. Do not apply blindly.
        if seq > st.last_applied_seq + 1 and st.last_applied_seq >= 0:
            st.needs_reconciliation = True
            # Caller is expected to issue tasks/get; we still apply the
            # event under rank rules but flag the gap.
            # (In production, return early and let reconciliation drive.)

        # Anomaly: seq advanced but rank regressed. Do not regress state.
        if rank < st.rank:
            st.last_applied_seq = seq  # advance to prevent re-processing
            st.needs_reconciliation = True
            raise NonMonotonicWebhookError(
                f"task {task_id}: seq={seq} rank={rank.name} regresses "
                f"current rank={st.rank.name}; state not applied"
            )

        # Safe apply: monotone in both seq and rank.
        st.rank = rank
        st.last_applied_seq = seq
        if artifact is not None:
            st.artifact = artifact

        # Idempotent side effect keyed by (task_id, seq).
        key = (task_id, seq)
        if key not in st.seen_side_effect_keys:
            st.seen_side_effect_keys.add(key)
            self._fire_side_effect(st)

        return st

    def _fire_side_effect(self, st: TaskState) -> None:
        # Downstream dispatch, completion callback, etc.
        pass
