# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-bind-its-oauth-2-1-resource-indicator-after-an-sse-session-resumption-and-why-the-last-event-id-is-not-enough.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-bind-its-oauth-2-1-resource-indicator-after-an-sse-session-resumption-and-why-the-last-event-id-is-not-enough.warrant.json
# Markdown SHA-256:   97438cff21b2752e32f464e09486b178e49c818df9ee53c6d089ff8615a0c1a0
# Code AST SHA-256:   70f451ca58687de0660ba5a98fe0d8dc3d9bf590c284160bbc16d161455a26db
# Verified Classes:   ResourceBindingMismatch, StreamAuthRecord, PresentedToken, ResumableStreamStore
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from typing import Optional


class ResourceBindingMismatch(RuntimeError):
    """Raised when an SSE resume cannot re-establish the stream's OAuth 2.1 resource binding."""


@dataclass(frozen=True)
class StreamAuthRecord:
    session_id: str
    stream_id: str
    resource_indicator: str
    principal: str


@dataclass(frozen=True)
class PresentedToken:
    principal: str
    resource_indicator: Optional[str]  # None == claim absent


def _indicator_hash(indicator: str) -> str:
    # RFC 8707 §2 canonicalization is assumed applied upstream; hash for partition keying.
    return hashlib.sha256(indicator.encode("utf-8")).hexdigest()


class ResumableStreamStore:
    def __init__(self) -> None:
        self._auth: dict[tuple[str, str], StreamAuthRecord] = {}
        self._log_partitions: dict[str, list[str]] = {}

    def open_stream(self, rec: StreamAuthRecord, first_events: list[str]) -> None:
        self._auth[(rec.session_id, rec.stream_id)] = rec
        self._log_partitions[_indicator_hash(rec.resource_indicator)] = list(first_events)

    def evict_auth_only(self, session_id: str, stream_id: str) -> None:
        # Simulates a restart / LRU that loses the auth record but keeps the log.
        self._auth.pop((session_id, stream_id), None)

    def resume(
        self,
        session_id: str,
        stream_id: str,
        last_event_id: int,
        token: PresentedToken,
    ) -> list[str]:
        record = self._auth.get((session_id, stream_id))

        if record is None:
            # Fail closed: the log may still exist, but we cannot prove authority over it.
            raise ResourceBindingMismatch(
                f"no auth record for {session_id}/{stream_id}; resume refused, re-initialize session"
            )

        if token.resource_indicator is None:
            raise ResourceBindingMismatch(
                f"resume for {session_id}/{stream_id} presented token with no resource indicator; "
                f"expected {record.resource_indicator!r}"
            )

        if token.resource_indicator != record.resource_indicator:
            raise ResourceBindingMismatch(
                f"resource indicator mismatch on resume: stream bound to "
                f"{record.resource_indicator!r}, token bound to {token.resource_indicator!r}"
            )

        if token.principal != record.principal:
            raise ResourceBindingMismatch(
                f"principal mismatch on resume: stream bound to {record.principal!r}, "
                f"token bound to {token.principal!r}"
            )

        partition = self._log_partitions.get(_indicator_hash(record.resource_indicator))
        if partition is None:
            raise ResourceBindingMismatch(
                f"log partition for {record.resource_indicator!r} missing; cannot replay"
            )
        return partition[last_event_id:]


def demo() -> None:
    store = ResumableStreamStore()
    store.open_stream(
        StreamAuthRecord("S", "1", "https://mcp.example.com/tenant-a", "alice"),
        ["e1", "e2", "e3", "e4"],
    )
    # Happy path: same resource, same principal.
    assert store.resume("S", "1", 3, PresentedToken("alice", "https://mcp.example.com/tenant-a")) == ["e4"]

    # Cross-tenant token: must not replay tenant-a events.
    try:
        store.resume("S", "1", 3, PresentedToken("alice", "https://mcp.example.com/tenant-b"))
    except ResourceBindingMismatch:
        pass
    else:
        raise AssertionError("cross-tenant resume was not rejected")

    # Auth record evicted, log retained: must fail closed, not trust the token.
    store.evict_auth_only("S", "1")
    try:
        store.resume("S", "1", 3, PresentedToken("alice", "https://mcp.example.com/tenant-a"))
    except ResourceBindingMismatch:
        pass
    else:
        raise AssertionError("orphaned log was replayed after auth eviction")


if __name__ == "__main__":
    demo()
