# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-upgrades-an-mcp-sse-session-to-streamable-http-mid-tool-call-and-the-oauth-2-1-resource-indicator-no-longer-matches-the.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-upgrades-an-mcp-sse-session-to-streamable-http-mid-tool-call-and-the-oauth-2-1-resource-indicator-no-longer-matches-the.warrant.json
# Markdown SHA-256:   c7b86a72b6ad3120e3e407f442d4519b11c7e2da80ff8e9637917ae8f2c90711
# Code AST SHA-256:   e710a930fa01d4093aca20df2e59811ef5a79255487b95591724ca352b85bb78
# Verified Classes:   ResourceIndicatorRebindingError, OrphanedToolCallError, Token, Session
# Defensive Guards:   4 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

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


class ResourceIndicatorRebindingError(RuntimeError):
    """Raised when an MCP transport upgrade changes the canonical resource URI
    such that the bearer token's audience no longer matches the live endpoint."""
    pass


class OrphanedToolCallError(RuntimeError):
    """Raised when a resume is attempted against a session whose in-flight tool
    call may still hold server-side resources; re-dispatch is unsafe."""
    pass


@dataclass
class Token:
    value: str
    audience: str          # the `resource` indicator this token was minted for
    active: bool = True


@dataclass
class Session:
    session_id: str
    transport: str                      # "sse" | "streamable_http"
    canonical_resource: str             # live endpoint's canonical URI
    last_event_id: int = 0
    in_flight_tool_call: Optional[str] = None
    token: Optional[Token] = None
    discovery_cache: dict = field(default_factory=dict)


def _canonicalize(uri: str) -> str:
    # Collapse scheme/port/trailing-slash/path-alias differences that are the
    # actual trigger for the rebinding gap.
    u = uri.strip()
    u = u.replace("http://", "https://", 1)
    u = u.rstrip("/")
    for alias in ("/sse", "/messages"):
        if u.endswith(alias):
            u = u[: -len(alias)] + "/mcp"
    return u


def resume_after_upgrade(session: Session, new_endpoint: str) -> Token:
    # (a) invalidate stale discovery cache from the pre-upgrade transport
    session.discovery_cache.clear()

    # (b) re-derive the live resource from the negotiated endpoint
    live_resource = _canonicalize(new_endpoint)
    session.canonical_resource = live_resource
    session.transport = "streamable_http"

    # (c) detect the rebinding gap before touching the network
    if session.token is None:
        raise ResourceIndicatorRebindingError(
            f"session {session.session_id}: no token present at upgrade"
        )
    if _canonicalize(session.token.audience) != live_resource:
        # The token is cryptographically fine but audience-bound to the old
        # transport. This is NOT an expiry; do not label it as one.
        raise ResourceIndicatorRebindingError(
            f"session {session.session_id}: token aud={session.token.audience!r} "
            f"does not match live resource {live_resource!r} after upgrade; "
            f"re-mint with resource={live_resource!r} (introspect.active="
            f"{session.token.active})"
        )

    # (d) resume, never re-dispatch. If a tool call is still in flight on the
    # server, replaying it would double-invoke a side-effecting tool.
    if session.in_flight_tool_call is not None and session.last_event_id == 0:
        raise OrphanedToolCallError(
            f"session {session.session_id}: tool {session.in_flight_tool_call!r} "
            f"in flight but no Last-Event-ID to resume from; refusing to "
            f"re-dispatch (lock/cursor may still be held server-side)"
        )

    return session.token


def handle_upgrade_response(session: Session, resp: dict) -> Token:
    endpoint = resp.get("endpoint")
    if not endpoint:
        raise ResourceIndicatorRebindingError(
            f"session {session.session_id}: upgrade response omitted canonical "
            f"resource; client cannot infer audience safely"
        )
    return resume_after_upgrade(session, endpoint)
