# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-streamable-http-session-resumption-against-an-sse-era-event-id-watermark-during-mcp-transport-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-streamable-http-session-resumption-against-an-sse-era-event-id-watermark-during-mcp-transport-migration.warrant.json
# Markdown SHA-256:   e8a5d85a539a0ce0b1fb468ede1df1402487a7eda4680573aef2ad4f1afc4a51
# Code AST SHA-256:   02be442598335b7d2dcf2207190627667bc4bbf29b6274c8a12e9f8d54c0d1a5
# Verified Classes:   CrossSessionReplayError, StreamCursor, SessionBoundCursorStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CrossSessionReplayError(RuntimeError):
    """Raised when a Last-Event-ID is presented against a session it was not minted under."""
    pass


@dataclass(frozen=True)
class StreamCursor:
    session_id: str
    last_event_id: str


class SessionBoundCursorStore:
    """Client-side guard: a cursor is only ever emitted with its birth session."""

    def __init__(self) -> None:
        self._cursor: StreamCursor | None = None

    def record(self, session_id: str, event_id: str) -> None:
        self._cursor = StreamCursor(session_id=session_id, last_event_id=event_id)

    def header_for(self, active_session_id: str) -> dict[str, str]:
        if self._cursor is None:
            return {}
        if self._cursor.session_id != active_session_id:
            # Do NOT carry the SSE-era or prior-session cursor forward.
            # Drop it and force an explicit re-sync instead.
            self._cursor = None
            raise CrossSessionReplayError(
                f"cursor minted under session {self._cursor_session_repr()} "
                f"cannot be sent to session {active_session_id}; "
                f"performing cold-start re-sync"
            )
        return {"Last-Event-ID": self._cursor.last_event_id}

    def _cursor_session_repr(self) -> str:
        return "<dropped>"


def open_stream(store: SessionBoundCursorStore, active_session_id: str) -> dict[str, str]:
    try:
        return store.header_for(active_session_id)
    except CrossSessionReplayError:
        # Re-sync path: re-list tools/resources before resuming.
        _resync_state()
        return {}


def _resync_state() -> None:
    # Placeholder for tools/list + resources/list + prompt cache invalidation.
    return None
