# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-continuity-when-an-mcp-session-migrates-from-resumable-sse-transport-to-streamable-http-mid-conversation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-continuity-when-an-mcp-session-migrates-from-resumable-sse-transport-to-streamable-http-mid-conversation.warrant.json
# Markdown SHA-256:   404b9bdd2fc348adbfe5a182081fb5beec058ed2a1be1f966295c345136325c2
# Code AST SHA-256:   8a706896a7678b9a0bef7f4beed5b516f9e790831fe508c47772f17ec468f6d1
# Verified Classes:   TransportMigrationError, ReplayObligationUnmet, SessionSnapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class TransportMigrationError(RuntimeError):
    """Raised when an MCP session migration would lose server-push events."""


class ReplayObligationUnmet(TransportMigrationError):
    """SSE cursor is behind the server log head and target transport cannot replay."""


@dataclass(frozen=True)
class SessionSnapshot:
    session_id: str
    last_seen_event_id: int      # client's SSE Last-Event-ID
    server_log_head_id: int      # server's current SSE log head for this session
    outstanding_calls: frozenset[int]   # JSON-RPC ids still owing notifications
    target_transport: str        # "streamable_http" | "sse"


def migrate_session(snap: SessionSnapshot, *, target_supports_replay: bool) -> str:
    """
    Enforce the quiescence barrier before allowing SSE -> streamable-HTTP migration.

    Invariant: migration is legal only if there are no owed-but-undelivered
    server-push events that the target transport cannot represent.
    """
    if snap.target_transport not in {"streamable_http", "sse"}:
        raise TransportMigrationError(f"unknown transport {snap.target_transport!r}")

    if snap.target_transport == "sse":
        # Staying on / moving to SSE: cursor semantics are native, no barrier needed
        # beyond normal resumption.
        return "sse"

    # Target is streamable HTTP: it has NO Last-Event-ID replay log.
    behind = snap.server_log_head_id - snap.last_seen_event_id
    owed_events = behind > 0
    owed_calls = len(snap.outstanding_calls) > 0

    if (owed_events or owed_calls) and not target_supports_replay:
        # The exact failure observed: completed results survive, completion
        # notifications do not, agent re-executes and diverges.
        raise ReplayObligationUnmet(
            "refusing SSE->streamable-HTTP migration: "
            f"last_seen={snap.last_seen_event_id} log_head={snap.server_log_head_id} "
            f"(owed_events={owed_events}) outstanding_calls={sorted(snap.outstanding_calls)} "
            "target transport cannot replay server-push events; "
            "drain to quiescence or require server-side notification replay"
        )

    if owed_events and target_supports_replay:
        # Legal only because server will re-emit missed notifications on the
        # new stream keyed by the carried cursor.
        return "streamable_http_with_replay"

    return "streamable_http"


def attempt_migration(snap: SessionSnapshot, *, target_supports_replay: bool) -> str:
    try:
        return migrate_session(snap, target_supports_replay=target_supports_replay)
    except ReplayObligationUnmet:
        # Fall back to draining on SSE rather than migrating mid-flight.
        return "sse_drain_then_retry"
