# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-negotiate-oauth-2-1-resource-indicators-when-an-mcp-sse-session-resumes-onto-a-streamable-http-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-negotiate-oauth-2-1-resource-indicators-when-an-mcp-sse-session-resumes-onto-a-streamable-http-transport.warrant.json
# Markdown SHA-256:   42c900fe93cd1be32076a12bbb3fc0c5a644ebba3f896b76dd38925dd8458ef3
# Code AST SHA-256:   913b00323143095f82a46c9689f0c0a1ebae7e39e813769282a1a2e8ed327eb3
# Verified Classes:   ResourceAudienceMismatch, SessionAuth
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ResourceAudienceMismatch(RuntimeError):
    """Raised when a resumed MCP session presents a token whose RFC 8707
    resource indicator does not match the current transport endpoint."""
    pass


@dataclass(frozen=True)
class SessionAuth:
    session_id: str
    endpoint_uri: str
    resource_indicator: str
    access_token: str


def resume_session(
    cached: SessionAuth,
    new_endpoint_uri: str,
    mint_token,  # callable(resource: str) -> str
) -> SessionAuth:
    # Invariant: session id survives transport change; audience does not.
    if cached.endpoint_uri != new_endpoint_uri:
        # Transport changed (SSE -> streamable HTTP). The cached resource
        # indicator is bound to the old URI and MUST NOT be reused.
        new_resource = new_endpoint_uri
        if cached.resource_indicator == new_resource:
            # Defensive: same URI but flagged as transitioned is a logic bug.
            raise ResourceAudienceMismatch(
                f"transport changed but resource unchanged: {new_resource}"
            )
        new_token = mint_token(new_resource)
        if not new_token:
            raise ResourceAudienceMismatch(
                f"could not mint token for resource {new_resource}; "
                f"escalate to full re-consent, preserve session {cached.session_id}"
            )
        return SessionAuth(
            session_id=cached.session_id,  # preserved across re-auth
            endpoint_uri=new_endpoint_uri,
            resource_indicator=new_resource,
            access_token=new_token,
        )
    return cached


def classify_401(www_authenticate: str, cached: SessionAuth, request_uri: str) -> str:
    if "resource mismatch" in www_authenticate:
        if cached.resource_indicator != request_uri:
            # Not expiry: audience failure. Refresh-with-same-resource forbidden.
            raise ResourceAudienceMismatch(
                f"audience failure on {request_uri}: "
                f"token bound to {cached.resource_indicator}; "
                f"re-authorize with resource={request_uri}, keep session "
                f"{cached.session_id}"
            )
        raise ResourceAudienceMismatch(
            f"server rejected matching resource {request_uri}; "
            f"possible per-verb resource split (POST vs GET)"
        )
    return "expiry"  # only non-audience 401s may take the refresh path
