# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-with-a-stale-last-event-id-after-the-server-has-already-garbage-collected-the-event-ring-buffe.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-with-a-stale-last-event-id-after-the-server-has-already-garbage-collected-the-event-ring-buffe.warrant.json
# Markdown SHA-256:   df0dab418832c8956078e534bbd6018c543313e24e1e24c2600fb8ea33e277c6
# Code AST SHA-256:   46b8f9c828e479b00f61c45cbd03829a20dc7cf7932b07fbb04bb0fbbc08448f
# Verified Classes:   StreamResumeGapError, SSEResumeCursor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class StreamResumeGapError(RuntimeError):
    """Raised when an SSE resume produces an event-ID discontinuity that the
    client cannot safely bridge without full state reconciliation."""


@dataclass
class SSEResumeCursor:
    session_id: str
    last_processed_event_id: int
    session_epoch: int
    pending_calls: dict = field(default_factory=dict)  # call_id -> idempotency_key


def resume_stream(cursor: SSEResumeCursor,
                  reconnect_epoch: int,
                  first_event_id: Optional[int]) -> None:
    """Validate that a reconnected SSE stream is a true continuation of `cursor`.

    Invariant: the first event received after reconnect MUST be exactly
    last_processed_event_id + 1, and the session epoch MUST be unchanged.
    Anything else means the server's event ring buffer evicted our cursor
    (or the session restarted) and the stream has forked.
    """
    if reconnect_epoch != cursor.session_epoch:
        raise StreamResumeGapError(
            f"session epoch changed {cursor.session_epoch}->{reconnect_epoch}; "
            f"event counter reset, cursor invalid, full resync required"
        )

    if first_event_id is None:
        raise StreamResumeGapError(
            "server opened stream but sent no event; cannot confirm continuity"
        )

    expected = cursor.last_processed_event_id + 1
    if first_event_id > expected:
        gap = first_event_id - expected
        orphaned = list(cursor.pending_calls.keys())
        raise StreamResumeGapError(
            f"cursor evicted: expected event {expected}, got {first_event_id} "
            f"(gap={gap}); {len(orphaned)} pending tool calls orphaned: {orphaned}. "
            f"Re-issue with idempotency keys and discard partial progress."
        )

    if first_event_id <= cursor.last_processed_event_id:
        # Duplicate replay from nearest retained event: dedupe, do not apply.
        raise StreamResumeGapError(
            f"regressed replay: got event {first_event_id} <= last processed "
            f"{cursor.last_processed_event_id}; dedupe by event ID before applying"
        )


def issue_tool_call(cursor: SSEResumeCursor, tool: str, args: dict) -> str:
    """Issue a tools/call with a stable idempotency key so post-gap re-issues
    are deduped server-side rather than double-executed."""
    call_id = str(uuid.uuid4())
    idem_key = f"{cursor.session_id}:{call_id}"
    cursor.pending_calls[call_id] = idem_key
    # ... POST JSON-RPC tools/call with idem_key in params._meta ...
    return call_id
