# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-resumable-sse-replay-as-a-fresh-authorization-event-rather-than-a-continuation-of-the-original-request.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-resumable-sse-replay-as-a-fresh-authorization-event-rather-than-a-continuation-of-the-original-request.warrant.json
# Markdown SHA-256:   fa4284627a9f41fc9c8761c8eb3738f4d5f1cd157e3300a6ea1d2b1709ec9243
# Code AST SHA-256:   54ec249c46d389a9208e2d34d729c2c4f7f7e5d7300f0125a94bc972b6ba4465
# Verified Classes:   ResumeAuthorizationMismatch, AuthContext, BufferedEvent, ResumableStream
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumeAuthorizationMismatch(RuntimeError):
    """Raised when an SSE resume presents a token whose authorization context
    does not match the context recorded when the stream was opened."""
    pass


@dataclass(frozen=True)
class AuthContext:
    resource: str
    subject: str
    scopes: frozenset[str]


@dataclass
class BufferedEvent:
    event_id: int
    payload: dict
    required_scopes: frozenset[str]
    generated_under: AuthContext


class ResumableStream:
    def __init__(self, stream_id: str, opened_under: AuthContext):
        self.stream_id = stream_id
        self.opened_under = opened_under
        self.buffer: list[BufferedEvent] = []

    def append(self, event: BufferedEvent) -> None:
        self.buffer.append(event)

    def replay(
        self,
        last_event_id: int,
        presented: AuthContext,
    ) -> list[dict]:
        # Invariant 1 & 2: resource and subject must be byte-identical.
        if presented.resource != self.opened_under.resource:
            raise ResumeAuthorizationMismatch(
                f"resource indicator changed on resume: "
                f"opened={self.opened_under.resource!r} "
                f"presented={presented.resource!r}"
            )
        if presented.subject != self.opened_under.subject:
            raise ResumeAuthorizationMismatch(
                f"subject changed on resume: "
                f"opened={self.opened_under.subject!r} "
                f"presented={presented.subject!r}"
            )

        # Invariant 3: per-event scope filter, not a blind cursor.
        out: list[dict] = []
        for ev in self.buffer:
            if ev.event_id <= last_event_id:
                continue
            if not ev.required_scopes.issubset(presented.scopes):
                out.append({
                    "event": "message",
                    "data": {
                        "replay_skipped": True,
                        "event_id": ev.event_id,
                        "reason": "insufficient_scope_on_resume",
                        "required": sorted(ev.required_scopes),
                        "presented": sorted(presented.scopes),
                    },
                })
                continue
            out.append(ev.payload)
        return out


def handle_resume(
    stream: Optional[ResumableStream],
    last_event_id: int,
    presented: AuthContext,
) -> list[dict]:
    if stream is None:
        raise ResumeAuthorizationMismatch(
            f"no buffered stream for Last-Event-ID={last_event_id}; "
            "client must re-initialize"
        )
    return stream.replay(last_event_id, presented)
