# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-as-unbound-after-an-oauth-2-1-token-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-as-unbound-after-an-oauth-2-1-token-rotation.warrant.json
# Markdown SHA-256:   de0118974f41436666dd006a8454ce34f657262b246aebe97d1da5fd26b5a1ff
# Code AST SHA-256:   45c0e0f369bf00589025cb81ed10c2157f27b7fa04ab29b773d1c470058437f0
# Verified Classes:   BindingResumptionError, TokenBinding, StreamRecord, ResumableStreamRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from typing import FrozenSet, Optional


class BindingResumptionError(RuntimeError):
    """Raised when an SSE resume attempt cannot be safely bound to a stream."""


@dataclass(frozen=True)
class TokenBinding:
    iss: str
    sub: str
    client_id: str
    aud: str
    scopes: FrozenSet[str]

    def identity(self) -> tuple[str, str, str, str]:
        return (self.iss, self.sub, self.client_id, self.aud)


@dataclass(frozen=True)
class StreamRecord:
    stream_id: str
    open_binding: TokenBinding
    last_event_seq: int
    partition_key: str


def _partition_key(b: TokenBinding, stream_id: str) -> str:
    h = hashlib.sha256()
    for part in (*b.identity(), stream_id):
        h.update(part.encode())
        h.update(b"\x00")
    return h.hexdigest()


class ResumableStreamRegistry:
    def __init__(self) -> None:
        self._streams: dict[str, StreamRecord] = {}

    def open(self, stream_id: str, binding: TokenBinding) -> StreamRecord:
        rec = StreamRecord(
            stream_id=stream_id,
            open_binding=binding,
            last_event_seq=0,
            partition_key=_partition_key(binding, stream_id),
        )
        self._streams[stream_id] = rec
        return rec

    def resume(
        self,
        stream_id: str,
        last_event_id: int,
        now_binding: TokenBinding,
    ) -> StreamRecord:
        rec = self._streams.get(stream_id)
        if rec is None:
            raise BindingResumptionError(
                f"unknown stream_id={stream_id!r}: cannot resume (410 Gone)"
            )

        open_b = rec.open_binding
        if open_b.identity() != now_binding.identity():
            raise BindingResumptionError(
                "binding_changed: token identity "
                f"{now_binding.identity()} != stream-open identity "
                f"{open_b.identity()} for stream_id={stream_id!r} (409)"
            )

        if not open_b.scopes.issubset(now_binding.scopes):
            missing = open_b.scopes - now_binding.scopes
            raise BindingResumptionError(
                f"insufficient_scope: resumed token missing {sorted(missing)} "
                f"required at stream open for stream_id={stream_id!r} (403)"
            )

        if last_event_id < 0 or last_event_id > rec.last_event_seq:
            raise BindingResumptionError(
                f"cursor_out_of_range: Last-Event-ID={last_event_id} not in "
                f"[0,{rec.last_event_seq}] for stream_id={stream_id!r} (400)"
            )

        # Cursor is resolved *within* the caller's partition, never globally.
        if _partition_key(now_binding, stream_id) != rec.partition_key:
            raise BindingResumptionError(
                f"partition_mismatch: cursor would cross binding partition "
                f"for stream_id={stream_id!r} (409)"
            )

        return rec


def resume_or_fail(
    registry: ResumableStreamRegistry,
    stream_id: str,
    last_event_id: int,
    now_binding: TokenBinding,
) -> StreamRecord:
    try:
        return registry.resume(stream_id, last_event_id, now_binding)
    except BindingResumptionError:
        # Surface to the client as a terminal resume failure; do not
        # silently fall back to a fresh stream at cursor 0.
        raise
