# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-invalid-when-the-oauth-2-1-resource-indicator-of-the-resumed-sessio.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-invalid-when-the-oauth-2-1-resource-indicator-of-the-resumed-sessio.warrant.json
# Markdown SHA-256:   9824d3bdcf4fc6a594014acc594ba1caf3eab7aae5f53debdcf386f31c5c8a8d
# Code AST SHA-256:   659b20319e3ad2dd6af3a98ddb539cfca8c8c100a02b401cc289c3b02cc872ee
# Verified Classes:   ResumptionAuthorizationError, ReplayedEvent, SessionAuth
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ResumptionAuthorizationError(RuntimeError):
    """Raised when a replayed SSE event cannot be bound to the current
    OAuth 2.1 resource indicator and registry epoch."""
    pass


@dataclass(frozen=True)
class ReplayedEvent:
    last_event_id: int
    tool: str
    resource: str          # RFC 8707 resource indicator bound at emission
    registry_epoch: str    # hash of server's tool->resource registry
    payload: dict


@dataclass(frozen=True)
class SessionAuth:
    session_id: str
    token_resource: str    # `resource` claim of the bearer used at reconnect
    current_registry_epoch: str


def apply_replayed_event(event: ReplayedEvent, auth: SessionAuth) -> dict:
    # Foreign audience: event belongs to a different authorization context.
    if event.resource != auth.token_resource:
        raise ResumptionAuthorizationError(
            f"event {event.last_event_id} for tool {event.tool!r} "
            f"bound to resource {event.resource!r}, "
            f"but session token audience is {auth.token_resource!r}; "
            f"replay is foreign, do not apply"
        )

    # Stale registry: resource indicator for this tool has rotated since emission.
    if event.registry_epoch != auth.current_registry_epoch:
        raise ResumptionAuthorizationError(
            f"event {event.last_event_id} for tool {event.tool!r} "
            f"emitted under registry epoch {event.registry_epoch!r}, "
            f"current epoch is {auth.current_registry_epoch!r}; "
            f"replay is descriptive only, re-issue the tool call"
        )

    return event.payload


def registry_epoch(tool_to_resource: dict[str, str]) -> str:
    canonical = "|".join(
        f"{k}={v}" for k, v in sorted(tool_to_resource.items())
    )
    return hashlib.sha256(canonical.encode()).hexdigest()[:16]
