# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-mcp-streamable-http-session-rather-than-silently-downgrade-to-sse-fallback.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-mcp-streamable-http-session-rather-than-silently-downgrade-to-sse-fallback.warrant.json
# Markdown SHA-256:   356fd5157bda318f5690af9eb4d8a92280e06dc84adef5ee733e5a77cc0c84d3
# Code AST SHA-256:   e75c2a27071ec7c4876b712769654c9acb5c87f53d938d5bfd9730c4d0f25fa8
# Verified Classes:   ResumptionImpossibleError, InboundRequest, SessionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumptionImpossibleError(RuntimeError):
    """Raised when a resuming client cannot be served and fallback would corrupt replay state."""
    pass


@dataclass
class InboundRequest:
    session_id: str | None
    last_event_id: int | None
    method: str


@dataclass
class SessionState:
    known: bool
    buffer_min_id: int | None   # lowest event id still replayable
    buffer_max_id: int | None   # highest event id produced


def negotiate_transport(req: InboundRequest, state: SessionState) -> str:
    """
    Returns one of: 'json', 'sse_live', 'sse_resume'.
    Raises ResumptionImpossibleError instead of silently falling back
    when the client asserts a replay position we cannot honor.
    """
    # Fresh client: no session, no replay obligation.
    if req.session_id is None and req.last_event_id is None:
        return "sse_live"

    # In-session request with no replay assertion.
    if req.last_event_id is None:
        if not state.known:
            # Session unknown but client asserts nothing: safe to start fresh.
            return "sse_live"
        return "json"

    # Client asserts replay position. This is the boundary.
    if not state.known:
        raise ResumptionImpossibleError(
            f"session {req.session_id!r} unknown on this node; "
            f"cannot resume from Last-Event-ID={req.last_event_id}. "
            "Refusing SSE fallback: it would reset the client's event sequence."
        )

    if state.buffer_min_id is None or state.buffer_max_id is None:
        raise ResumptionImpossibleError(
            f"session {req.session_id!r} has no replay buffer; "
            f"Last-Event-ID={req.last_event_id} cannot be honored."
        )

    if req.last_event_id < state.buffer_min_id - 1:
        raise ResumptionImpossibleError(
            f"Last-Event-ID={req.last_event_id} already evicted "
            f"(buffer starts at {state.buffer_min_id}); replay would skip events."
        )

    if req.last_event_id > state.buffer_max_id:
        raise ResumptionImpossibleError(
            f"Last-Event-ID={req.last_event_id} exceeds produced max "
            f"{state.buffer_max_id}; client is ahead of server state."
        )

    return "sse_resume"
