# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resume-a-streamed-mcp-session-into-a-half-open-eventsource-and-silently-lose-tool-call-results.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resume-a-streamed-mcp-session-into-a-half-open-eventsource-and-silently-lose-tool-call-results.warrant.json
# Markdown SHA-256:   fc1ebab69af42a9b5847a46ccb1996fc1124494c9579e262c7d2cb682b00e139
# Code AST SHA-256:   c83590b79dca62cd3296a2e11384b36d53cdd927ea5c1570a751fb408bf1b60a
# Verified Classes:   ResumptionGapError, ResumeState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class ResumptionGapError(RuntimeError):
    """Raised when the client's consumed cursor has fallen below the
    server's replay-retention floor, or when the client is asked to
    resume from an event the server never emitted. Both mean the
    tool-call result may have been lost and the side-effect status
    is unknown; the caller must reconcile, not blindly retry."""


@dataclass(frozen=True)
class ResumeState:
    consumed_cursor: int      # highest event_id handed to dispatcher (NOT parsed)
    parsed_cursor: int        # highest event_id tokenized by the SSE reader
    server_min_retained: int  # oldest event_id the server can still replay
    server_max_emitted: int   # newest event_id the server has assigned


def build_resume_header(state: ResumeState, *, dedupe_floor: int) -> str:
    """Compute the Last-Event-ID to send on reconnect.

    Invariant: the cursor is a function of *dispatch*, never of *receipt*.
    Any frame parsed-but-not-dispatched is unacknowledged and must be replayed.
    """
    if state.consumed_cursor > state.parsed_cursor:
        # Impossible: you cannot dispatch a frame you have not parsed.
        raise ResumptionGapError(
            f"consumed_cursor {state.consumed_cursor} exceeds parsed_cursor "
            f"{state.parsed_cursor}; cursor bookkeeping is corrupted"
        )

    if state.parsed_cursor != state.consumed_cursor:
        # Backpressure drift: parser ran ahead of dispatcher. This is the
        # dangerous window. We resume from the *consumed* cursor so the
        # server replays everything the dispatcher never accepted.
        pass

    if state.consumed_cursor + 1 < state.server_min_retained:
        raise ResumptionGapError(
            f"consumed_cursor {state.consumed_cursor} is below server retention "
            f"floor {state.server_min_retained}; events are irrecoverably evicted "
            f"and the tool-call result cannot be replayed"
        )

    if state.consumed_cursor > state.server_max_emitted:
        # The future-cursor bug: we claim to have consumed events that were
        # never emitted (classic symptom of a receipt-advanced cursor).
        raise ResumptionGapError(
            f"consumed_cursor {state.consumed_cursor} exceeds server_max_emitted "
            f"{state.server_max_emitted}; refusing to resume from a fabricated future"
        )

    if state.consumed_cursor < dedupe_floor:
        raise ResumptionGapError(
            f"consumed_cursor {state.consumed_cursor} precedes dedupe_floor "
            f"{dedupe_floor}; dispatcher cannot guarantee event_id deduplication"
        )

    return str(state.consumed_cursor)


def dispatch_frame(frame_event_id: int, dispatcher_consumed: int) -> int:
    """Advance the consumed cursor ONLY after the dispatcher accepts a frame.

    Called from the SSE reader after the dispatcher returns for the payload
    carrying frame_event_id. Returns the new consumed cursor.
    """
    if frame_event_id <= dispatcher_consumed:
        # Duplicate replay; dispatcher already handled it. Do not re-dispatch.
        return dispatcher_consumed
    if frame_event_id != dispatcher_consumed + 1:
        raise ResumptionGapError(
            f"non-contiguous dispatch: got event_id {frame_event_id} after "
            f"{dispatcher_consumed}; a frame was skipped and its result is lost"
        )
    return frame_event_id
