# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-resume-an-mcp-http-native-sse-stream-versus-reinitialize-the-session.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-resume-an-mcp-http-native-sse-stream-versus-reinitialize-the-session.warrant.json
# Markdown SHA-256:   3a567c3c2c0199989d5baeee72e9b0248f7e85d834bbea4e004aab7de109d42b
# Code AST SHA-256:   bad753d640b97fac362b1ac42ed017c16cdff78182f1ce522c3d62e89a040b78
# Verified Classes:   McpStreamResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class McpStreamResumeError(RuntimeError):
    """Raised when an SSE resume request cannot be honored safely."""

    def __init__(self, session_id: str, last_event_id: str | None, reason: str):
        self.session_id = session_id
        self.last_event_id = last_event_id
        self.reason = reason
        super().__init__(
            f"cannot resume session={session_id!r} cursor={last_event_id!r}: {reason}"
        )


def decide_resume_action(
    session_id: str,
    last_event_id: str | None,
    *,
    session_live: bool,
    stream_generation_live: bool,
    retained_log_ids: set[str],
    head_event_id: str | None,
) -> str:
    # Unknown or retired session: never resume.
    if not session_live:
        raise McpStreamResumeError(session_id, last_event_id, "session unknown or retired")

    # Stream generation retired (drain, capability change, explicit close):
    # the cursor namespace is invalid; force reinitialization.
    if not stream_generation_live:
        raise McpStreamResumeError(
            session_id, last_event_id, "stream generation retired; cursor namespace invalid"
        )

    # No cursor presented: this is a fresh stream, not a resume.
    if last_event_id is None:
        return "open_fresh_stream"

    # Cursor ahead of head implies ID reuse across generations: reject.
    if head_event_id is not None and _is_ahead(last_event_id, head_event_id):
        raise McpStreamResumeError(
            session_id, last_event_id, "cursor ahead of head; probable event-ID reuse"
        )

    # Cursor not in retained log: cannot replay without loss.
    if last_event_id not in retained_log_ids:
        raise McpStreamResumeError(
            session_id, last_event_id, "cursor evicted from retained event log"
        )

    return "resume_with_replay"


def _is_ahead(cursor: str, head: str) -> bool:
    try:
        return int(cursor) > int(head)
    except ValueError:
        return False


def handle_resume_request(session_id: str, last_event_id: str | None, server_state) -> int:
    try:
        action = decide_resume_action(
            session_id,
            last_event_id,
            session_live=server_state.session_live(session_id),
            stream_generation_live=server_state.stream_generation_live(session_id),
            retained_log_ids=server_state.retained_log_ids(session_id),
            head_event_id=server_state.head_event_id(session_id),
        )
    except McpStreamResumeError as exc:
        # Force the client toward reinitialization; never answer with 200 + empty replay.
        server_state.metrics.increment("resume_rejected", reason=exc.reason)
        return 404 if "session unknown" in exc.reason else 409

    if action == "resume_with_replay":
        server_state.metrics.increment("resume_with_replay")
        return 200
    server_state.metrics.increment("open_fresh_stream")
    return 200
