# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-stream-resumption-as-unsafe-the-last-event-id-replay-gap-under-backpressure.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-stream-resumption-as-unsafe-the-last-event-id-replay-gap-under-backpressure.warrant.json
# Markdown SHA-256:   c713c459675730bbc46e76061afab7190bdf5f26c62143ff6dc05adedb6a1793
# Code AST SHA-256:   0d6b4297a0c388f1f001fa548d6bb5f26feb53926b67b41b49cd3e3db68a21c2
# Verified Classes:   StreamResumeGapError, ResumeVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StreamResumeGapError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot be proven contiguous."""


@dataclass(frozen=True)
class ResumeVerdict:
    contiguous: bool
    skipped: int
    action: str


def evaluate_resume(
    last_event_id: int,
    emission_cursor: int,
    oldest_retained_id: int,
    server_clamped_silently: bool,
    terminal_event_pinned: bool,
) -> ResumeVerdict:
    # A resumed stream is only safe if the server can replay (last_event_id, cursor].
    if last_event_id > emission_cursor:
        raise StreamResumeGapError(
            f"client ack {last_event_id} is ahead of server cursor {emission_cursor}; "
            "stream identity mismatch — refuse to merge"
        )

    if last_event_id == emission_cursor:
        return ResumeVerdict(contiguous=True, skipped=0, action="no-op")

    replayable = last_event_id >= oldest_retained_id - 1

    if replayable and not server_clamped_silently:
        return ResumeVerdict(contiguous=True, skipped=0, action="merge")

    skipped = max(0, oldest_retained_id - 1 - last_event_id)

    if server_clamped_silently and skipped > 0:
        # The dangerous case: client cannot see the gap from the stream itself.
        raise StreamResumeGapError(
            f"server clamped resume from ack {last_event_id} to {oldest_retained_id} "
            f"without gap marker; {skipped} events unrecoverable and undetectable in-band"
        )

    if not terminal_event_pinned:
        raise StreamResumeGapError(
            "terminal event not pinned in retention; completed/incomplete state "
            "is indeterminate across resume"
        )

    return ResumeVerdict(contiguous=False, skipped=skipped, action="mark_incomplete_escalate")


def merge_resumed_stream(verdict: ResumeVerdict, prior_state: dict, new_events: list) -> dict:
    if not verdict.contiguous:
        # Never merge a partial stream into durable agent state as if complete.
        raise StreamResumeGapError(
            f"refusing to merge {len(new_events)} events after a {verdict.skipped}-event "
            f"gap; action={verdict.action}"
        )
    merged = dict(prior_state)
    merged.setdefault("events", []).extend(new_events)
    return merged
