# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-last-event-id-against-a-re-negotiated-transport-before-resuming-an-mcp-sse-stream-that-fell-back-to-streamable-http.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-last-event-id-against-a-re-negotiated-transport-before-resuming-an-mcp-sse-stream-that-fell-back-to-streamable-http.warrant.json
# Markdown SHA-256:   dd21bbf41d3138acf601c4a095990063f577c7bdccaf14695b2fdd3367c39804
# Code AST SHA-256:   d30a1c6ef97c8281bfd063412e353018f7d5d209b81570e3b3c3c645a356e7bf
# Verified Classes:   CursorNamespaceMismatch, StreamContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CursorNamespaceMismatch(RuntimeError):
    """Raised when a Last-Event-ID cursor is carried across a transport,
    session, or event-id-namespace change and would be misaddressed."""
    pass


@dataclass(frozen=True)
class StreamContext:
    transport: str          # "sse" | "streamable-http"
    session_id: str
    event_id_namespace: str
    last_event_id: int


def resume_stream(prior: StreamContext, current: StreamContext) -> Optional[int]:
    """Decide whether to carry the cursor or force cold resumption.

    Returns the Last-Event-ID to send, or None to signal cold resumption.
    Raises CursorNamespaceMismatch if the caller attempts to carry a cursor
    across an incompatible context (defense in depth: the caller should have
    branched on None, not reached the raise path).
    """
    same_transport = prior.transport == current.transport
    same_session = prior.session_id == current.session_id
    same_namespace = prior.event_id_namespace == current.event_id_namespace

    if same_transport and same_session and same_namespace:
        # Safe: standard SSE resumption within one namespace.
        return prior.last_event_id

    # Any component of the triple changed: the cursor is not addressable
    # in the new context. Cold resumption is mandatory.
    if same_session and not same_namespace:
        # Server reused the session id but re-rooted the counter. This is the
        # silent-corruption case: numeric comparison will not reject it.
        raise CursorNamespaceMismatch(
            f"session {current.session_id!r} reused across namespace change "
            f"{prior.event_id_namespace!r} -> {current.event_id_namespace!r}; "
            f"cursor {prior.last_event_id} is not addressable"
        )

    # Transport or session changed: return None to force cold resumption.
    # Do NOT send prior.last_event_id as Last-Event-ID.
    return None


def apply_resumption(prior: StreamContext, current: StreamContext) -> str:
    cursor = resume_stream(prior, current)
    if cursor is None:
        return (
            "COLD_RESUME: reconcile tools/list and in-flight progressTokens "
            "against session " + current.session_id + " before resuming live"
        )
    return f"RESUME_FROM: Last-Event-ID={cursor}"
