# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-negotiate-mcp-resource-indicators-after-an-sse-to-streamable-http-session-migration-and-why-token-binding-silently-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-negotiate-mcp-resource-indicators-after-an-sse-to-streamable-http-session-migration-and-why-token-binding-silently-diverges.warrant.json
# Markdown SHA-256:   4d97ba6c1afba8c867caa7e4dde87a22fa74a6a4db180e5115ff9c790ecd3c86
# Code AST SHA-256:   c3deb5df27743ff01a37982e613b89c54458b7f65d0a3aca8676e849cb13710e
# Verified Classes:   ResourceIndicatorMismatch, Token
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from urllib.parse import urlparse

class ResourceIndicatorMismatch(RuntimeError):
    """Raised when a migrated session's bearer token no longer covers the invoked resource."""
    pass

@dataclass(frozen=True)
class Token:
    bearer: str
    resource: str          # RFC 8707 resource indicator claim
    expires_at: int

def _normalize(uri: str) -> str:
    p = urlparse(uri)
    return f"{p.scheme}://{p.netloc}{p.path.rstrip('/')}"

def assert_migration_auth_continuity(
    pre_migration_endpoint: str,
    post_migration_tool_resource: str,
    token: Token,
    server_uses_origin_fallback: bool,
) -> None:
    """
    Enforce the invariant: a transport migration that changes the canonical
    resource MUST invalidate the token, regardless of Last-Event-ID replay success.

    Called BEFORE the first tools/call after migration. Raises if the token's
    resource claim does not exactly cover the post-migration tool resource.
    """
    token_res = _normalize(token.resource)
    tool_res = _normalize(post_migration_tool_resource)

    if token_res == tool_res:
        return  # binding intact

    # Origin fallback is the silent-failure path: server may accept, but the
    # binding is still wrong and downstream strict matching will reject.
    if server_uses_origin_fallback:
        tok_origin = urlparse(token.resource)
        tool_origin = urlparse(post_migration_tool_resource)
        if (tok_origin.scheme, tok_origin.netloc) == (tool_origin.scheme, tool_origin.netloc):
            raise ResourceIndicatorMismatch(
                f"Silent divergence: token resource {token.resource!r} origin-matches "
                f"tool resource {post_migration_tool_resource!r} but does not cover it. "
                f"Server origin-fallback would accept; downstream strict match will fail. "
                f"Re-mint token against {post_migration_tool_resource!r} before tools/call."
            )

    raise ResourceIndicatorMismatch(
        f"Token resource {token.resource!r} (minted for pre-migration endpoint "
        f"{pre_migration_endpoint!r}) does not cover post-migration tool resource "
        f"{post_migration_tool_resource!r}. Last-Event-ID replay success is NOT "
        f"evidence of auth continuity. Re-authorize with RFC 8707 re-mint."
    )

def resume_after_migration(
    last_event_id: str,
    pre_migration_endpoint: str,
    first_tool_resource: str,
    token: Token,
    server_uses_origin_fallback: bool,
) -> str:
    # Step 1: replay the event stream (message continuity only).
    replay_ok = last_event_id is not None and last_event_id != ""
    if not replay_ok:
        raise ResourceIndicatorMismatch("No Last-Event-ID; cannot resume message stream.")

    # Step 2: independently enforce credential-binding continuity.
    assert_migration_auth_continuity(
        pre_migration_endpoint=pre_migration_endpoint,
        post_migration_tool_resource=first_tool_resource,
        token=token,
        server_uses_origin_fallback=server_uses_origin_fallback,
    )

    return hashlib.sha256(f"{last_event_id}:{first_tool_resource}".encode()).hexdigest()
