# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-stream-when-the-server-s-last-event-id-replay-window-has-already-been-evicted-by-backpressure-driven-co.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-stream-when-the-server-s-last-event-id-replay-window-has-already-been-evicted-by-backpressure-driven-co.warrant.json
# Markdown SHA-256:   eb55f768d19ced7328ce2f1b844e6ad3a0a2cb346e2ab759c98e379b0261de62
# Code AST SHA-256:   707a1f5537fdda6e75bab2d0d6ef16a12f7f712013a6d6ff615c902ee52d58f7
# Verified Classes:   McpResumeGapError, ResumeContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import dataclasses
from typing import Optional


class McpResumeGapError(RuntimeError):
    """Raised when a resumed MCP stream cannot prove cursor continuity."""


@dataclasses.dataclass(frozen=True)
class ResumeContext:
    last_event_id: str
    first_delivered_id: Optional[str]
    server_retention_events: Optional[int]   # None == server did not advertise a bound
    pending_request_ids: frozenset[str]     # sampling/elicitation requests awaiting reply
    pending_tool_call_ids: frozenset[str]   # tools/call in flight (idempotency keys)
    missed_event_classes: frozenset[str]    # best-effort classification of the gap


def _is_successor(prev: str, nxt: str) -> bool:
    # Event ids are opaque per spec; only numeric ids admit a cheap successor check.
    try:
        return int(nxt) == int(prev) + 1
    except (TypeError, ValueError):
        return False


def reconcile_resume(ctx: ResumeContext) -> str:
    """
    Returns one of: "continue", "reconcile_tools", "reset".
    Raises McpResumeGapError when continuity cannot be established and the
    caller has not opted into reset.
    """
    if ctx.first_delivered_id is None:
        # Stream opened but delivered nothing; not a gap, just an empty resume.
        return "continue"

    contiguous = _is_successor(ctx.last_event_id, ctx.first_delivered_id)

    if contiguous:
        return "continue"

    # Non-successor first event: a gap exists. Decide based on in-flight state.
    if ctx.pending_request_ids:
        # A lost sampling/elicitation request gates a tool call; cannot recover in-stream.
        raise McpResumeGapError(
            f"resume gap swallowed pending request(s) {sorted(ctx.pending_request_ids)}; "
            f"cursor={ctx.last_event_id} first={ctx.first_delivered_id}; must reset"
        )

    if ctx.pending_tool_call_ids:
        # Outcome of in-flight tool calls is unknown; never re-issue, reconcile by key.
        raise McpResumeGapError(
            f"resume gap hides completion of tool call(s) {sorted(ctx.pending_tool_call_ids)}; "
            f"reconcile by idempotency key, do not retry"
        )

    if "notifications/tools/list_changed" in ctx.missed_event_classes:
        # Delta signal lost; tool cache is stale even though nothing was in flight.
        return "reconcile_tools"

    if ctx.server_retention_events is None:
        # No advertised bound: cannot prove the gap was bounded, so cannot trust it.
        raise McpResumeGapError(
            f"server advertised no retention bound and gap detected "
            f"(cursor={ctx.last_event_id} first={ctx.first_delivered_id})"
        )

    return "reset"
