# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-across-an-sse-to-post-fallback-without-renegotiating-the-event-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-mcp-session-across-an-sse-to-post-fallback-without-renegotiating-the-event-cursor.warrant.json
# Markdown SHA-256:   93ccbbd04e5bb8fb4029a2ca25dcf61b70aec41010f12038edbcb1b06ac80757
# Code AST SHA-256:   164abbe76bcdcfe0020e9a4e7a096c36b44c3a5d892ca9ee65d829c17440b347
# Verified Classes:   CursorContinuityError, SessionState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CursorContinuityError(RuntimeError):
    """Raised when an event-consuming request cannot prove cursor continuity."""


@dataclass
class SessionState:
    session_id: str
    last_event_id: int = -1
    channel: str = "sse"  # "sse" | "post"
    seen_ids: set[int] = field(default_factory=set)


def build_event_request(state: SessionState, *, new_channel: str) -> dict:
    """Construct headers for an event-consuming request on either channel."""
    if new_channel not in ("sse", "post"):
        raise CursorContinuityError(f"unknown channel {new_channel!r}")

    headers = {"Mcp-Session-Id": state.session_id}

    # Invariant: the cursor is session-scoped. Any channel transition must
    # carry the last-seen event id, or the request is a non-authoritative
    # resync and must be flagged as such.
    if state.last_event_id >= 0:
        headers["Last-Event-ID"] = str(state.last_event_id)
    elif state.channel != new_channel:
        # No cursor yet but switching channels: this is a fresh consumer on a
        # live session. Refuse silently forking the event sequence.
        raise CursorContinuityError(
            f"channel switch {state.channel}->{new_channel} with no cursor; "
            "cannot guarantee event continuity"
        )

    return headers


def ingest_event(state: SessionState, event_id: int, payload: dict) -> bool:
    """Apply an event, deduplicating by id. Returns True if newly applied."""
    if event_id in state.seen_ids:
        return False  # at-least-once replay: drop duplicate
    if event_id != state.last_event_id + 1 and state.last_event_id >= 0:
        # Gap detected: server skipped events. Do not silently advance.
        raise CursorContinuityError(
            f"event gap: expected {state.last_event_id + 1}, got {event_id}"
        )
    state.seen_ids.add(event_id)
    state.last_event_id = event_id
    # ... dispatch payload to reducer here ...
    return True


def fallback_to_post(state: SessionState) -> dict:
    """Degrade SSE->POST. Must preserve cursor or refuse."""
    headers = build_event_request(state, new_channel="post")
    state.channel = "post"
    return headers
