# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-resumed-mcp-stream-the-last-event-id-replay-gap-in-streamable-http-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-resumed-mcp-stream-the-last-event-id-replay-gap-in-streamable-http-sessions.warrant.json
# Markdown SHA-256:   26706a6933bc9d1be0c48d113ffe8c8ec71afb5ba46e3bbf983208656f705fb9
# Code AST SHA-256:   05f58674ce652cd6304a90f89c65230c19d07e331d55b7e41264f38238cae319
# Verified Classes:   StreamContinuityError, ResumedStreamGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StreamContinuityError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven continuous
    with the client's applied event history."""
    pass


@dataclass
class ResumedStreamGuard:
    session_id: str
    session_epoch: str
    last_applied_id: Optional[str] = None
    _applied: set = field(default_factory=set)

    def _parse_seq(self, event_id: str) -> int:
        # event IDs are "<epoch>:<seq>"; seq is monotonic within an epoch
        epoch, _, seq = event_id.partition(":")
        if epoch != self.session_epoch:
            raise StreamContinuityError(
                f"epoch mismatch: event {event_id!r} belongs to epoch "
                f"{epoch!r}, client bound to {self.session_epoch!r} "
                f"(session {self.session_id})"
            )
        try:
            return int(seq)
        except ValueError as exc:
            raise StreamContinuityError(
                f"unparseable event id {event_id!r} in session {self.session_id}"
            ) from exc

    def accept(self, event_id: str) -> bool:
        """Return True if event should be applied, False if it is a
        benign duplicate. Raise if continuity is violated."""
        seq = self._parse_seq(event_id)

        if event_id in self._applied:
            return False  # exact duplicate: safe no-op

        if self.last_applied_id is None:
            self._applied.add(event_id)
            self.last_applied_id = event_id
            return True

        expected = self._parse_seq(self.last_applied_id) + 1
        if seq == expected:
            self._applied.add(event_id)
            self.last_applied_id = event_id
            return True

        if seq < expected:
            # counter reset or replay of a *different* event with same seq
            raise StreamContinuityError(
                f"non-monotonic resume: got seq {seq}, expected {expected} "
                f"(last applied {self.last_applied_id!r}, event {event_id!r}) "
                f"in session {self.session_id}; reconcile from server snapshot"
            )

        # seq > expected: silent gap, events were evicted or dropped
        raise StreamContinuityError(
            f"gap detected: got seq {seq}, expected {expected} "
            f"({seq - expected} event(s) missing) in session "
            f"{self.session_id}; abandon incremental continuation"
        )


def resume_stream(guard: ResumedStreamGuard, events: list[str]) -> list[str]:
    """Apply a resumed SSE batch; refuse to continue on divergence."""
    applied = []
    for event_id in events:
        if guard.accept(event_id):
            applied.append(event_id)
        # duplicates are dropped silently by design
    if not applied and events:
        raise StreamContinuityError(
            f"resumed stream for session {guard.session_id} delivered "
            f"{len(events)} events but none were new; server may have "
            f"replayed a stale snapshot instead of honoring Last-Event-ID"
        )
    return applied
