# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumed-mcp-sse-stream-has-silently-lost-its-oauth-2-1-resource-server-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-resumed-mcp-sse-stream-has-silently-lost-its-oauth-2-1-resource-server-binding.warrant.json
# Markdown SHA-256:   ef40b664584e7f9ca3b7b0fcfcbd4f539418786b213f41ad446a048624aa6250
# Code AST SHA-256:   0ceca5142e85a43fa20d04dbe28dcebaddc728c345114f56a6eb4cf05b272911
# Verified Classes:   ResumptionBindingError, StreamBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ResumptionBindingError(RuntimeError):
    """Raised when an SSE resumption would cross an OAuth 2.1 resource-server binding boundary."""


@dataclass(frozen=True)
class StreamBinding:
    session_id: str
    resource_indicator: str
    token_jti: str
    grant_id: str


def _indicator_hash(indicator: str) -> str:
    return hashlib.sha256(indicator.encode("utf-8")).hexdigest()


def resume_stream(
    *,
    stored: StreamBinding,
    presented_indicator: str,
    presented_jti: str,
    presented_grant_id: str,
    last_event_id: int,
    buffer_has_events_after: bool,
) -> int:
    """
    Decide whether a resumption request may replay buffered events.

    Returns the last_event_id to replay from on success.
    Raises ResumptionBindingError on any binding mismatch, BEFORE touching the buffer.
    """
    if _indicator_hash(stored.resource_indicator) != _indicator_hash(presented_indicator):
        raise ResumptionBindingError(
            f"resource indicator mismatch on resumption: "
            f"stream bound to {stored.resource_indicator!r}, "
            f"token presents {presented_indicator!r}; "
            f"refusing replay of events after id={last_event_id}"
        )

    same_grant = presented_grant_id == stored.grant_id
    same_jti = presented_jti == stored.token_jti
    if not (same_grant or same_jti):
        raise ResumptionBindingError(
            f"token not part of original authorization grant: "
            f"stream grant={stored.grant_id!r} jti={stored.token_jti!r}, "
            f"presented grant={presented_grant_id!r} jti={presented_jti!r}"
        )

    if not buffer_has_events_after:
        # Nothing to replay; still a valid resumption, but caller must not
        # assume continuity beyond last_event_id.
        return last_event_id

    return last_event_id


def client_guard_before_resume(
    *,
    creation_indicator: str,
    current_indicator: str,
    last_event_id: int,
) -> Optional[int]:
    """
    Client-side guard: return last_event_id to resume from, or None to force
    a fresh stream (discard replay buffer, re-plan from checkpoint).
    """
    if _indicator_hash(creation_indicator) != _indicator_hash(current_indicator):
        # Do NOT resume. The replay buffer was produced under a different
        # authorization binding; consuming it would cross the boundary.
        return None
    return last_event_id
