# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-reattached-mcp-sse-stream-whose-oauth-resource-binding-was-silently-re-scoped-between-last-event-id-and-session-rebind.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-reattached-mcp-sse-stream-whose-oauth-resource-binding-was-silently-re-scoped-between-last-event-id-and-session-rebind.warrant.json
# Markdown SHA-256:   6de792be58712c9e4fcb36bc8af1dd1751300bce7ccbb5b29d61d34f70838e50
# Code AST SHA-256:   f4c2dabc901d97c415d899746829a61b79a3604bbd14ecab2f0cdc6f542740b4
# Verified Classes:   ResourceBindingMismatch, SessionRecord, AccessToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResourceBindingMismatch(RuntimeError):
    """Raised when a resumed SSE session's OAuth resource binding does not
    match the resource of the token presented on reattach. Replaying buffered
    events under a mismatched binding is a confidentiality/integrity breach."""


@dataclass
class SessionRecord:
    session_id: str
    resource_binding: Optional[str]   # captured at initialize(); None == legacy/unbound
    event_buffer: list
    expires_at: float


@dataclass
class AccessToken:
    resource: str
    exp: float


def reattach(
    session: Optional[SessionRecord],
    token: AccessToken,
    last_event_id: int,
    now: float,
) -> list:
    if session is None:
        raise ResourceBindingMismatch(
            f"unknown session; cannot resume Last-Event-ID={last_event_id}"
        )

    if session.expires_at <= now:
        raise ResourceBindingMismatch(
            f"session {session.session_id} expired at {session.expires_at}"
        )

    if token.exp <= now:
        raise ResourceBindingMismatch(
            f"token expired at {token.exp}; refresh before reattach"
        )

    # The invariant that naive servers skip: binding must be present AND equal.
    if session.resource_binding is None:
        raise ResourceBindingMismatch(
            f"session {session.session_id} has no recorded resource binding; "
            "refusing to replay — force fresh initialize"
        )

    if token.resource != session.resource_binding:
        raise ResourceBindingMismatch(
            f"resource re-scoped on reattach: session bound to "
            f"{session.resource_binding!r}, token presents {token.resource!r}; "
            "replay aborted to prevent capability drift"
        )

    # Safe to replay: binding, session liveness, and token liveness all hold.
    return session.event_buffer[last_event_id:]
