# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-resumed-mcp-stream-as-a-new-session-rather-than-a-continuation-and-why-the-wire-cannot-tell-you.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-resumed-mcp-stream-as-a-new-session-rather-than-a-continuation-and-why-the-wire-cannot-tell-you.warrant.json
# Markdown SHA-256:   aac104c3ef3f33d62a2ae2c0996fbef5966976b362e82c358bea8a82c755e059
# Code AST SHA-256:   19d891ae3c746842639e959fed39aa05c09899455a4beed30ba38b2dead15f7e
# Verified Classes:   StreamResumptionGap, ResumeOutcome
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class StreamResumptionGap(RuntimeError):
    """Raised when a resumed MCP stream's first event ID is not the
    immediate successor of the Last-Event-ID the client presented.

    Signals that events were lost (ring-buffer eviction, restart, or a
    foreign server instance) and the session must be re-initialized
    rather than continued.
    """


_EVT_RE = re.compile(r"^evt-(\d+)$")


def _parse_event_id(raw: str) -> int:
    m = _EVT_RE.match(raw)
    if not m:
        raise StreamResumptionGap(f"unparseable event id: {raw!r}")
    return int(m.group(1))


@dataclass
class ResumeOutcome:
    action: str  # "continue" | "reinitialize"
    reason: str


def classify_resume(requested_last_event_id: str, first_received_id: str) -> ResumeOutcome:
    """Decide whether a resumption GET is a true continuation.

    The server cannot be trusted to signal a gap; only the client knows
    which ID it asked for. Any non-successor first ID is a hard fault.
    """
    try:
        req = _parse_event_id(requested_last_event_id)
        got = _parse_event_id(first_received_id)
    except StreamResumptionGap as exc:
        # Unparseable IDs mean we cannot prove continuity -> reinitialize.
        return ResumeOutcome("reinitialize", f"id scheme mismatch: {exc}")

    if got == req + 1:
        return ResumeOutcome("continue", "immediate successor")

    if got > req + 1:
        raise StreamResumptionGap(
            f"silent gap on resume: requested {requested_last_event_id}, "
            f"first received {first_received_id}; "
            f"{got - req - 1} event(s) lost, session state may be stale"
        )

    # got <= req: server reset its ID space (new instance / restart).
    raise StreamResumptionGap(
        f"id space reset on resume: requested {requested_last_event_id}, "
        f"first received {first_received_id}; treating as new session"
    )


def resume_stream(transport, session) -> ResumeOutcome:
    """Wrap a resumption GET so a gap can never be silently absorbed."""
    requested = session.last_event_id
    first = transport.open_resumed_stream(last_event_id=requested)
    outcome = classify_resume(requested, first)
    if outcome.action == "reinitialize":
        session.reinitialize()
    else:
        session.last_event_id = first
    return outcome
