# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-http-native-sse-resumption-has-silently-invalidated-a-per-tool-oauth-2-1-resource-indicator-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-http-native-sse-resumption-has-silently-invalidated-a-per-tool-oauth-2-1-resource-indicator-binding.warrant.json
# Markdown SHA-256:   f225c23fc5384fcb8d3d56b3a92723f974340d0f779f1de838c5a81829d46ed2
# Code AST SHA-256:   72487b6472a2ac20d6ae2a03af02c8c778d12aa809cfcb9c45e62339be6e44fc
# Verified Classes:   ResourceIndicatorResumeError, BufferedEvent
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class ResourceIndicatorResumeError(RuntimeError):
    """Raised when an SSE resume would replay events authorized under a
    resource indicator not covered by the presented token."""


@dataclass(frozen=True)
class BufferedEvent:
    event_id: int
    payload: dict
    authorized_resource: str  # stamp written at emission time


def resume_stream(
    last_event_id: int,
    buffer: Iterable[BufferedEvent],
    token_resource: str,
    session_tool_binding: str,
) -> list[BufferedEvent]:
    """Re-validate every replayed event's authorization stamp against the
    presented token before allowing resumption."""
    replay_window = [e for e in buffer if e.event_id > last_event_id]

    if not replay_window:
        return []

    unauthorized = [
        e for e in replay_window if e.authorized_resource != token_resource
    ]

    if unauthorized:
        raise ResourceIndicatorResumeError(
            f"Resume from Last-Event-ID={last_event_id} would replay "
            f"{len(unauthorized)} event(s) authorized under "
            f"{ {e.authorized_resource for e in unauthorized} } "
            f"but token is scoped to {token_resource!r}. "
            f"Session binding {session_tool_binding!r} does not authorize "
            f"replay; refusing to continue stream."
        )

    return replay_window
