# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-cursors-against-streamable-http-resumption-tokens-when-migrating-mcp-transport-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-sse-event-id-cursors-against-streamable-http-resumption-tokens-when-migrating-mcp-transport-mid-session.warrant.json
# Markdown SHA-256:   95718b3f8ed91bf9b11810740d5326bee8a58f2a0eb56a98245a59d9fbdb167e
# Code AST SHA-256:   b4fc96a7f000983398ced8a53f87988a5c538b94ee6a030beb2255860f51ae73
# Verified Classes:   ResumptionCursorMismatch, Cursor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionCursorMismatch(RuntimeError):
    """Raised when a resumption cursor is presented across a transport/session boundary."""


@dataclass(frozen=True)
class Cursor:
    family: str          # "sse" or "sth"
    session_id: str
    event_id: str


def reanchor_cursor(
    cursor: Optional[Cursor],
    target_family: str,
    target_session_id: str,
    last_acked_req_id: Optional[str],
) -> Optional[str]:
    """
    Return a Last-Event-ID safe to send to the target endpoint, or None to
    let the server replay from its session buffer. Fails closed on mismatch.
    """
    if cursor is None:
        return None

    same_family = cursor.family == target_family
    same_session = cursor.session_id == target_session_id

    if same_family and same_session:
        return cursor.event_id

    # Cross-transport or cross-session: the opaque cursor is not portable.
    # We may only re-anchor if the client has a committed JSON-RPC ack.
    if last_acked_req_id is None:
        raise ResumptionCursorMismatch(
            f"cursor {cursor.family}:{cursor.session_id}:{cursor.event_id} "
            f"cannot be presented to {target_family}:{target_session_id} "
            f"and no acknowledged request ID is available to re-anchor"
        )

    # Re-anchor: discard the transport token, signal buffer replay by
    # omitting Last-Event-ID. The server replays from its retained buffer;
    # idempotency on (session, jsonrpc.id) prevents duplicate side effects.
    return None


def build_resume_request(
    cursor: Optional[Cursor],
    target_family: str,
    target_session_id: str,
    last_acked_req_id: Optional[str],
    pending_body: dict,
) -> dict:
    last_event_id = reanchor_cursor(
        cursor, target_family, target_session_id, last_acked_req_id
    )
    headers = {"Mcp-Session-Id": target_session_id}
    if last_event_id is not None:
        headers["Last-Event-ID"] = last_event_id
    # Idempotency key is mandatory once we have crossed a boundary.
    if cursor is not None and (
        cursor.family != target_family or cursor.session_id != target_session_id
    ):
        if "id" not in pending_body:
            raise ResumptionCursorMismatch(
                "pending request lacks jsonrpc id; cannot dedupe after re-anchor"
            )
        headers["Idempotency-Key"] = f"{target_session_id}:{pending_body['id']}"
    return {"headers": headers, "body": pending_body}
