# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-sse-event-id-cursor-after-mcp-streamable-http-reconnection-when-the-oauth-2-1-resource-server-binding-has-rotated.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-sse-event-id-cursor-after-mcp-streamable-http-reconnection-when-the-oauth-2-1-resource-server-binding-has-rotated.warrant.json
# Markdown SHA-256:   f4c97d885e921e05508315ffb56ad46a22e0ed0113d46cc69904164c5a256026
# Code AST SHA-256:   ac0a56c851288a29d450474e74ce681024d1a23638a3a68e465410b3fca20dc0
# Verified Classes:   StaleEpochResumptionError, AuthEpoch, StreamEvent
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleEpochResumptionError(RuntimeError):
    """Raised when a Last-Event-ID resumption crosses an authorization epoch boundary."""
    pass


@dataclass(frozen=True)
class AuthEpoch:
    audience: str
    key_id: str

    def fingerprint(self) -> str:
        return hashlib.sha256(f"{self.audience}|{self.key_id}".encode()).hexdigest()[:16]


@dataclass(frozen=True)
class StreamEvent:
    event_id: int
    epoch: AuthEpoch
    payload: dict


def resume_stream(
    last_event_id: int,
    presented_token_epoch: AuthEpoch,
    replay_buffer: list[StreamEvent],
) -> list[StreamEvent]:
    """
    Enforce the invariant: every replayed event's epoch must equal the
    presented token's epoch. A cryptographically valid token whose epoch
    has rotated since the events were produced must NOT be allowed to
    resume into the old scope.
    """
    replay = [e for e in replay_buffer if e.event_id > last_event_id]
    if not replay:
        return []

    want = presented_token_epoch.fingerprint()
    for event in replay:
        if event.epoch.fingerprint() != want:
            raise StaleEpochResumptionError(
                f"resumption from Last-Event-ID={last_event_id} would cross "
                f"epoch boundary: token epoch {want} vs event {event.event_id} "
                f"epoch {event.epoch.fingerprint()} "
                f"(aud={event.epoch.audience}, kid={event.epoch.key_id}). "
                f"Reject with 409 and force re-initialize."
            )
    return replay
