# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-across-an-oauth-2-1-token-rotation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-sse-stream-across-an-oauth-2-1-token-rotation-boundary.warrant.json
# Markdown SHA-256:   32add7328701b8fdf331f44ca0c20090766b22ec2dfa37bed64fdebe3a8bab31
# Code AST SHA-256:   9f7427c29980ce09ae12561ceade5e2df4e87546f98d3f5536f3d580e1ce1460
# Verified Classes:   ResumptionContextMismatch, TokenExpired, AuthContext, BufferedEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional
import time


class ResumptionContextMismatch(RuntimeError):
    """Raised when a resumed SSE stream presents an authorization context
    that does not match the context captured at stream establishment."""
    pass


class TokenExpired(RuntimeError):
    pass


@dataclass(frozen=True)
class AuthContext:
    sub: str
    canonical_resource: str
    scope: str

    def matches(self, other: "AuthContext") -> bool:
        return (
            self.sub == other.sub
            and self.canonical_resource == other.canonical_resource
            and self.scope == other.scope
        )


@dataclass
class BufferedEvent:
    event_id: int
    payload: dict
    enqueued_under: AuthContext
    enqueued_at: float


def canonicalize_resource(indicator: str) -> str:
    # RFC 8707 resource indicators are URIs; normalize scheme/host casing
    # and strip a single trailing slash so equality is stable.
    s = indicator.strip()
    if s.endswith("/") and s.count("/") > 2:
        s = s[:-1]
    scheme, rest = s.split("://", 1)
    host, *path = rest.split("/", 1)
    normalized = f"{scheme.lower()}://{host.lower()}"
    if path:
        normalized += "/" + path[0]
    return normalized


def resume_stream(
    cursor: int,
    presented: AuthContext,
    session_context: Optional[AuthContext],
    buffer: list[BufferedEvent],
    token_expires_at: float,
    now: Optional[float] = None,
) -> list[BufferedEvent]:
    now = now if now is not None else time.time()

    if token_expires_at <= now:
        raise TokenExpired(
            f"token for sub={presented.sub} expired at {token_expires_at}"
        )

    if session_context is None:
        raise ResumptionContextMismatch(
            f"no session context recorded for cursor={cursor}; "
            "refusing to replay from an unbound buffer"
        )

    if not session_context.matches(presented):
        # Do NOT fall through to replay. The buffer was produced under a
        # different authorization context and is not transferable.
        raise ResumptionContextMismatch(
            "resumption authorization context does not match stream "
            f"establishment context: session={session_context!r} "
            f"presented={presented!r}"
        )

    replay = [e for e in buffer if e.event_id > cursor]

    for e in replay:
        if not e.enqueued_under.matches(presented):
            raise ResumptionContextMismatch(
                f"event {e.event_id} was enqueued under {e.enqueued_under!r} "
                f"but resumption presents {presented!r}"
            )

    return replay
