# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-sse-to-post-upgrade-boundary-in-mcp-streamable-session-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-sse-to-post-upgrade-boundary-in-mcp-streamable-session-resumption.warrant.json
# Markdown SHA-256:   95a7a6058af3bff0ccdd642ca63729851be036eb88fc19b6f761deb1d8411964
# Code AST SHA-256:   5e4032551016237f7fc12cc96c677c8f4b7a4bbdc3b229ff067b4286b269e436
# Verified Classes:   ChannelState, StreamableSessionError, OutboxEntry, StreamableSession
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ChannelState(Enum):
    SSE = "sse"
    POST = "post"
    RECONNECTING = "reconnecting"


class StreamableSessionError(RuntimeError):
    """Raised when a streamable MCP session's channel state would strand messages."""


@dataclass
class OutboxEntry:
    seq: int
    delivered: bool = False


@dataclass
class StreamableSession:
    session_id: str
    channel: ChannelState = ChannelState.SSE
    outbox: list[OutboxEntry] = field(default_factory=list)
    last_client_event_id: int = 0
    replay_window: int = 100

    def _undelivered(self) -> list[OutboxEntry]:
        return [e for e in self.outbox if not e.delivered]

    def handle_resume(self, last_event_id: int) -> None:
        # Boundary: a resume asserts the SSE channel is the client's live path.
        # Either re-home the outbox onto the stream atomically, or reject.
        undelivered = self._undelivered()
        if undelivered and undelivered[0].seq < (last_event_id - self.replay_window):
            raise StreamableSessionError(
                f"resume_unavailable: session {self.session_id} outbox head "
                f"seq={undelivered[0].seq} precedes replay window floor "
                f"{last_event_id - self.replay_window}; open a new session"
            )
        if undelivered and any(e.seq <= last_event_id for e in undelivered):
            raise StreamableSessionError(
                f"resume_ordering_violation: session {self.session_id} has "
                f"undelivered seq <= Last-Event-ID {last_event_id}; "
                f"outbox drain must precede live-tail attach"
            )
        # Atomic transition: flip channel and drain are one critical section.
        self.channel = ChannelState.SSE
        for entry in undelivered:
            entry.delivered = True
        self.last_client_event_id = last_event_id

    def handle_post(self, response_event_seq: int) -> None:
        if self.channel is ChannelState.RECONNECTING:
            raise StreamableSessionError(
                f"post_during_reconnect: session {self.session_id} SSE channel "
                f"is reconnecting; POST would create a second live channel"
            )
        # POST acceptance must not silently flip channel state; outbox writes
        # for side-channel notifications must be reconciled before the flip.
        self.outbox.append(OutboxEntry(seq=response_event_seq))
        if self.channel is ChannelState.SSE:
            # Do not flip to POST here; the SSE channel remains the read path.
            return
        self.channel = ChannelState.POST

    def drain_outbox_on_stream(self) -> list[int]:
        delivered = [e.seq for e in self._undelivered()]
        for e in self._undelivered():
            e.delivered = True
        return delivered
