# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-stream-resumption-with-session-resumption-when-an-mcp-server-s-sse-event-id-and-session-id-diverge-across-a-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-stream-resumption-with-session-resumption-when-an-mcp-server-s-sse-event-id-and-session-id-diverge-across-a-reconnect.warrant.json
# Markdown SHA-256:   3f9d6fa3885bd5f9e605bc62b57a41520d5a1896ca480c92b70a5d3e9c189691
# Code AST SHA-256:   c76047bd08b514fb37c115d2b3c567bef24a6c643a0c75e788de65791888ca0e
# Verified Classes:   ResumptionState, ResumptionDivergence, ResumeToken
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ResumptionState(Enum):
    RESUME_STREAM = "resume_stream"          # live session + valid event id
    FRESH_STREAM = "fresh_stream"            # live session, no usable event id
    NEW_SESSION = "new_session"              # dead session, discard event id
    SPLIT_BRAIN = "split_brain"              # 200 stream but session rejected


class ResumptionDivergence(RuntimeError):
    """Raised when stream cursor and session identity cannot be jointly validated."""


@dataclass
class ResumeToken:
    session_id: str
    last_event_id: int
    session_epoch: int  # epoch the event id belonged to


def classify_reconnect(
    token: ResumeToken,
    session_live: bool,
    stream_returns_200: bool,
    outbound_post_ok: bool,
    server_event_epoch: int,
) -> ResumptionState:
    # Split-brain: stream says 200 but the session layer rejects our writes.
    if stream_returns_200 and not outbound_post_ok:
        return ResumptionState.SPLIT_BRAIN

    if not session_live:
        # Event id belongs to a dead session; the replay buffer is not ours.
        return ResumptionState.NEW_SESSION

    # Session is live, but the event id may have been minted under a prior epoch.
    if token.session_epoch != server_event_epoch:
        return ResumptionState.FRESH_STREAM

    return ResumptionState.RESUME_STREAM


def build_resume_request(token: ResumeToken, state: ResumptionState) -> dict:
    headers = {"Mcp-Session-Id": token.session_id}

    if state is ResumptionState.RESUME_STREAM:
        headers["Last-Event-ID"] = str(token.last_event_id)
    elif state is ResumptionState.FRESH_STREAM:
        # Live session, but do not replay a foreign epoch's events.
        pass
    elif state is ResumptionState.NEW_SESSION:
        # Must re-establish; the caller is responsible for a new session id.
        headers.pop("Mcp-Session-Id", None)
    elif state is ResumptionState.SPLIT_BRAIN:
        raise ResumptionDivergence(
            f"stream 200 but session {token.session_id} rejects outbound POSTs; "
            "event id replay would splice dead-session events into a live stream"
        )

    return headers


if __name__ == "__main__":
    stale = ResumeToken(session_id="7f3a-c1", last_event_id=4812, session_epoch=1)
    state = classify_reconnect(
        stale,
        session_live=False,
        stream_returns_200=True,
        outbound_post_ok=False,
        server_event_epoch=2,
    )
    # Split-brain is detected before any replay is attempted.
    build_resume_request(stale, state)  # raises ResumptionDivergence
