# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-tool-call-loss-when-an-mcp-streamable-sse-session-resumes-across-a-last-event-id-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-tool-call-loss-when-an-mcp-streamable-sse-session-resumes-across-a-last-event-id-gap.warrant.json
# Markdown SHA-256:   adc7fcd5a329b6b6e191906c5dc5953e5438c260a6b78e504c77c4e38ec17f89
# Code AST SHA-256:   c972134a061daf2cb13bfbc6bd3ee6c1970fc100a558c6e64d4eac9a42597db4
# Verified Classes:   StreamResumeGapError, Idempotency, OutstandingCall, ResumeLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class StreamResumeGapError(RuntimeError):
    """Raised when an SSE resume cannot prove contiguity for outstanding requests."""


class Idempotency(Enum):
    IDEMPOTENT = "idempotent"
    NON_IDEMPOTENT = "non_idempotent"


@dataclass
class OutstandingCall:
    jsonrpc_id: int
    idempotency: Idempotency
    tool: str


@dataclass
class ResumeLedger:
    """Tracks in-flight tool calls across an SSE stream disconnect.

    The invariant enforced here: on resume, the first replayed frame must be
    exactly `last_event_id + 1`. If it is not, every outstanding call is
    indeterminate and must be reconciled by idempotency class -- never
    silently resumed and never blindly retried.
    """

    session_id: str
    last_event_id: int = 0
    outstanding: dict[int, OutstandingCall] = field(default_factory=dict)

    def on_disconnect(self, in_flight: list[OutstandingCall]) -> None:
        # Snapshot the outstanding set at the moment the stream dies.
        self.outstanding = {c.jsonrpc_id: c for c in in_flight}

    def on_first_resume_frame(self, first_replayed_id: int) -> list[OutstandingCall]:
        """Validate contiguity of the resumed stream.

        Returns the list of calls that must be reconciled (possibly empty).
        Raises StreamResumeGapError if the gap is unrecoverable AND any
        outstanding call is non-idempotent -- the caller must not proceed.
        """
        expected = self.last_event_id + 1
        if first_replayed_id == expected:
            return []  # contiguous; outstanding calls remain valid, resume normally

        # Gap detected. All outstanding calls are now indeterminate.
        indeterminate = list(self.outstanding.values())
        non_idempotent = [
            c for c in indeterminate if c.idempotency is Idempotency.NON_IDEMPOTENT
        ]
        if non_idempotent:
            raise StreamResumeGapError(
                f"session {self.session_id}: resume gap "
                f"expected id {expected}, got {first_replayed_id}; "
                f"{len(non_idempotent)} non-idempotent call(s) in indeterminate "
                f"state: {[c.tool for c in non_idempotent]}. "
                f"Refusing to resume; reconcile via idempotency endpoint or fail task."
            )
        # Only idempotent calls outstanding: safe to re-issue with fresh IDs.
        return indeterminate

    def on_frame(self, event_id: int) -> None:
        if event_id != self.last_event_id + 1:
            raise StreamResumeGapError(
                f"session {self.session_id}: non-contiguous frame "
                f"(expected {self.last_event_id + 1}, got {event_id})"
            )
        self.last_event_id = event_id

    def resolve(self, jsonrpc_id: int) -> None:
        self.outstanding.pop(jsonrpc_id, None)


def resume_agent_stream(
    ledger: ResumeLedger, first_replayed_id: int
) -> list[OutstandingCall]:
    """Entry point the agent loop calls immediately after SSE reconnect."""
    return ledger.on_first_resume_frame(first_replayed_id)
