# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-silently-corrupting-resumable-mcp-sessions-across-server-restarts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-event-id-reuse-from-silently-corrupting-resumable-mcp-sessions-across-server-restarts.warrant.json
# Markdown SHA-256:   e9466020d3614a5089ebdaf4a5289ee20ebe3508d0c0a0b0d31064166b06ac57
# Code AST SHA-256:   9198126a775b44a50e2dc5c7b38e744b85b28b2773dd0175eedf28f5bae06790
# Verified Classes:   ResumeIncoherentError, ResumeDecision
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class ResumeIncoherentError(RuntimeError):
    """Raised when a resumable MCP session cannot guarantee event-ID continuity."""


@dataclass(frozen=True)
class ResumeDecision:
    accept: bool
    replay_from: Optional[int]
    reason: str


def evaluate_resume(
    *,
    session_token_valid: bool,
    stream_identity_matches: bool,
    durable_log_low_watermark: Optional[int],
    durable_log_high_watermark: Optional[int],
    last_event_id: Optional[int],
    process_event_counter_start: int,
) -> ResumeDecision:
    """
    Decide whether a Last-Event-ID resume can be honored without breaking the
    event-ID-to-message bijection invariant.

    Returns a ResumeDecision. Raises ResumeIncoherentError if the caller has
    supplied state that cannot correspond to a coherent session (e.g. a valid
    token with no stream identity and no log), because proceeding would force
    a silent fall-through.
    """
    if not session_token_valid:
        return ResumeDecision(False, None, "session token invalid or expired")

    if not stream_identity_matches:
        # Token survived but the stream it referred to did not. Refuse.
        return ResumeDecision(False, None, "stream identity changed across restart")

    if last_event_id is None:
        # Fresh stream, no resume requested. Safe to start live.
        return ResumeDecision(True, None, "no resume requested; starting fresh")

    if durable_log_low_watermark is None or durable_log_high_watermark is None:
        # A resume was requested but there is no durable log to replay from.
        # The only coherent options are reject or invalidate; we reject.
        raise ResumeIncoherentError(
            f"resume requested at Last-Event-ID={last_event_id} but no durable "
            f"event log exists; refusing to fall through to live streaming with "
            f"process counter starting at {process_event_counter_start}"
        )

    if last_event_id < durable_log_low_watermark - 1:
        # Requested cursor predates the log (compaction). Cannot replay.
        return ResumeDecision(
            False,
            None,
            f"Last-Event-ID={last_event_id} below log low-watermark "
            f"{durable_log_low_watermark}; replay impossible",
        )

    if last_event_id > durable_log_high_watermark:
        # Cursor is ahead of anything we ever emitted on this stream. Either a
        # client bug or a token from a different stream incarnation.
        raise ResumeIncoherentError(
            f"Last-Event-ID={last_event_id} exceeds durable high-watermark "
            f"{durable_log_high_watermark}; cursor cannot belong to this stream"
        )

    return ResumeDecision(
        True,
        last_event_id + 1,
        f"replaying from durable log at {last_event_id + 1}",
    )


def client_accept_resumed_frame(
    *,
    cursor: int,
    incoming_event_id: int,
    dense_numbering: bool,
) -> int:
    """
    Client-side guard. Returns the new cursor, or raises if the resumed frame
    is incoherent with the cursor. This is the check that was missing in the
    incident: a decreasing or gapped id must abort, not reset.
    """
    if dense_numbering:
        if incoming_event_id != cursor + 1:
            raise ResumeIncoherentError(
                f"dense stream expected id {cursor + 1}, got {incoming_event_id}; "
                f"session poisoned, re-initialize required"
            )
    else:
        if incoming_event_id <= cursor:
            raise ResumeIncoherentError(
                f"sparse stream got non-advancing id {incoming_event_id} "
                f"after cursor {cursor}; session poisoned, re-initialize required"
            )
    return incoming_event_id
