# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-across-sse-to-streamable-http-migration-while-the-oauth-2-1-resource-indicator-no-longer-matches.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-across-sse-to-streamable-http-migration-while-the-oauth-2-1-resource-indicator-no-longer-matches.warrant.json
# Markdown SHA-256:   55a9dadb9a4ca82fae32664e3475a13a5d190e5e069295f22c649fae97e35faa
# Code AST SHA-256:   db4774b70aa9bf01fe34211c3add3733a6d3026045ae3a949d647c56bc4eb478
# Verified Classes:   AudienceMismatchOnResume, SessionRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class AudienceMismatchOnResume(RuntimeError):
    """Raised when a resumable MCP session is resumed under a different
    OAuth 2.1 resource indicator than the one bound at session creation."""


@dataclass
class SessionRecord:
    session_id: str
    bound_audience: str          # RFC 8707 resource indicator at creation
    transport: str               # "sse" | "streamable-http"
    replay_buffer: list = field(default_factory=list)  # [(event_id, audience, payload)]
    in_flight_tool: Optional[dict] = None


def resume_session(
    store: dict,
    session_id: str,
    presented_audience: str,
    presented_transport: str,
    last_event_id: int,
    policy: str = "strict",      # "strict" | "rebind" | "transport-scoped"
) -> dict:
    rec = store.get(session_id)
    if rec is None:
        raise AudienceMismatchOnResume(
            f"session {session_id} not found; cannot resume"
        )

    # Policy C: transport-scoped sessions forbid migration entirely.
    if policy == "transport-scoped" and presented_transport != rec.transport:
        raise AudienceMismatchOnResume(
            f"session {session_id} bound to transport {rec.transport!r}; "
            f"resume on {presented_transport!r} refused"
        )

    if presented_audience != rec.bound_audience:
        if policy == "strict":
            # Distinguishable error so the client does NOT blindly re-init
            # and double-execute a non-idempotent in-flight tool.
            raise AudienceMismatchOnResume(
                f"audience mismatch on resume of {session_id}: "
                f"bound={rec.bound_audience!r} presented={presented_audience!r}; "
                f"in_flight_tool={rec.in_flight_tool!r}; "
                f"do_not_reinit_without_idempotency_check"
            )
        elif policy == "rebind":
            # Re-scope replay: drop events the new audience is not entitled to.
            scoped = [
                (eid, aud, payload)
                for (eid, aud, payload) in rec.replay_buffer
                if aud == presented_audience
            ]
            rec.replay_buffer = scoped
            rec.bound_audience = presented_audience
            rec.transport = presented_transport
            return {
                "session_id": session_id,
                "rebound_audience": presented_audience,
                "replayed": [eid for (eid, _, _) in scoped if eid > last_event_id],
                "audience_changed": True,
            }
        else:
            raise AudienceMismatchOnResume(
                f"unknown policy {policy!r}"
            )

    # Audience matches: safe to replay from cursor.
    replayed = [
        (eid, payload)
        for (eid, aud, payload) in rec.replay_buffer
        if eid > last_event_id and aud == rec.bound_audience
    ]
    rec.transport = presented_transport
    return {
        "session_id": session_id,
        "rebound_audience": rec.bound_audience,
        "replayed": [eid for (eid, _) in replayed],
        "audience_changed": False,
    }
