# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-resumable-sse-last-event-id-replay-as-non-authoritative-against-side-effecting-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-resumable-sse-last-event-id-replay-as-non-authoritative-against-side-effecting-tool-calls.warrant.json
# Markdown SHA-256:   f226b48a289e59bf4f31fab78efa6a95a34cdc9ca10c0a3d42b466448d66357c
# Code AST SHA-256:   bbd4380441a32bde6c113ac3a9463f3b951cdbec633c564b6a40aa04d8f5dfa5
# Verified Classes:   ReplayCorrelationError, PendingState, PendingRequest, McpResumableClient
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import enum
from dataclasses import dataclass, field
from typing import Any


class ReplayCorrelationError(RuntimeError):
    """Raised when a replayed SSE event cannot be safely correlated to a
    pending request, and re-dispatch would risk a duplicate side effect."""


class PendingState(enum.Enum):
    IN_FLIGHT = "in_flight"
    UNKNOWN = "unknown"          # stream dropped; outcome not yet known
    SATISFIED = "satisfied"
    FAILED = "failed"


@dataclass
class PendingRequest:
    jsonrpc_id: str
    tool: str
    idempotent: bool
    state: PendingState = PendingState.IN_FLIGHT
    client_request_id: str = ""


@dataclass
class McpResumableClient:
    session_id: str
    pending: dict[str, PendingRequest] = field(default_factory=dict)
    last_event_id: int = 0
    consumed_event_ids: set[int] = field(default_factory=set)

    def on_stream_error(self, jsonrpc_id: str) -> None:
        """A dropped SSE stream is NOT a failed call. Mark UNKNOWN."""
        req = self.pending.get(jsonrpc_id)
        if req is None:
            raise ReplayCorrelationError(
                f"stream error for unknown request {jsonrpc_id!r}"
            )
        req.state = PendingState.UNKNOWN

    def on_replayed_event(self, event_id: int, payload: dict[str, Any]) -> None:
        """Handle an SSE event delivered via Last-Event-ID replay.

        Invariant: a replayed event is an OBSERVATION of past execution.
        It must never trigger re-dispatch of a side-effecting tool.
        """
        if event_id in self.consumed_event_ids:
            # Transport-level duplicate; idempotent to ignore.
            return
        self.consumed_event_ids.add(event_id)

        jsonrpc_id = payload.get("id")
        if jsonrpc_id is None:
            # Progress / message notification. Consume, do not act.
            return

        req = self.pending.get(jsonrpc_id)
        if req is None:
            # The result's request correlation was lost across reconnect.
            # Re-dispatching here would duplicate a side effect.
            raise ReplayCorrelationError(
                "replayed result event has no pending correlation entry; "
                f"jsonrpc_id={jsonrpc_id!r} event_id={event_id} "
                f"session={self.session_id!r}. Refusing to re-dispatch."
            )

        if req.state is PendingState.SATISFIED:
            return  # already consumed
        if "result" in payload or "error" in payload:
            req.state = PendingState.SATISFIED

    def redispatch(self, jsonrpc_id: str) -> str:
        """Only legal when the tool is idempotent AND a stable
        client_request_id is reused so the server can dedupe."""
        req = self.pending.get(jsonrpc_id)
        if req is None:
            raise ReplayCorrelationError(
                f"cannot re-dispatch unknown request {jsonrpc_id!r}"
            )
        if req.state is not PendingState.UNKNOWN:
            raise ReplayCorrelationError(
                f"re-dispatch forbidden in state {req.state.value} "
                f"for {jsonrpc_id!r}"
            )
        if not req.idempotent:
            raise ReplayCorrelationError(
                f"re-dispatch of non-idempotent tool {req.tool!r} "
                f"(jsonrpc_id={jsonrpc_id!r}) would duplicate a side effect; "
                "escalate to operator reconciliation"
            )
        req.state = PendingState.IN_FLIGHT
        return req.client_request_id
