# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-stream-mcp-sse-resumption-that-silently-re-binds-a-stale-oauth-2-1-resource-indicator-to-a-replayed-event-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-stream-mcp-sse-resumption-that-silently-re-binds-a-stale-oauth-2-1-resource-indicator-to-a-replayed-event-cursor.warrant.json
# Markdown SHA-256:   b129ee3d3250fb250482093c0c2c422674fb03b787162319191e4698410ccc99
# Code AST SHA-256:   bb20a0d613a4d969e92da80aaf760f68a1898ea33273bea25e33ff72a689e631
# Verified Classes:   StreamRebindError, SessionBinding
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class StreamRebindError(RuntimeError):
    """Raised when an SSE resume would silently re-bind a stale cursor to a new grant."""


@dataclass(frozen=True)
class SessionBinding:
    resource_indicator: str  # normalized RFC 3986 URI
    grant_fingerprint: str   # hash of (client_id, jti lineage, subject)
    cursor_epoch: str        # server-side event-id epoch marker


def _normalize_resource(uri: str) -> str:
    # Minimal normalization: strip trailing slash, lowercase scheme+host.
    if "://" not in uri:
        raise StreamRebindError(f"resource indicator not absolute: {uri!r}")
    scheme, rest = uri.split("://", 1)
    host, _, path = rest.partition("/")
    return f"{scheme.lower()}://{host.lower()}/{path.rstrip('/')}"


def _grant_fingerprint(client_id: str, jti_lineage: str, subject: str) -> str:
    h = hashlib.sha256()
    h.update(f"{client_id}\x00{jti_lineage}\x00{subject}".encode())
    return h.hexdigest()[:16]


def validate_resume(
    prior: SessionBinding,
    token_resource: str,
    token_client_id: str,
    token_jti_lineage: str,
    token_subject: str,
    server_cursor_epoch: str,
) -> SessionBinding:
    """Return the binding to use for the resumed stream, or raise if resume is unsafe."""
    new_resource = _normalize_resource(token_resource)
    if new_resource != prior.resource_indicator:
        raise StreamRebindError(
            f"resource indicator changed across resume: "
            f"{prior.resource_indicator!r} -> {new_resource!r}"
        )

    new_grant = _grant_fingerprint(token_client_id, token_jti_lineage, token_subject)
    if new_grant != prior.grant_fingerprint:
        raise StreamRebindError(
            f"grant lineage changed across resume: "
            f"{prior.grant_fingerprint} -> {new_grant}; "
            f"Last-Event-ID is not valid under the new grant"
        )

    if server_cursor_epoch != prior.cursor_epoch:
        raise StreamRebindError(
            f"server event-id epoch changed: "
            f"{prior.cursor_epoch!r} -> {server_cursor_epoch!r}; "
            f"cursor may alias a prior-epoch event"
        )

    return SessionBinding(
        resource_indicator=new_resource,
        grant_fingerprint=new_grant,
        cursor_epoch=server_cursor_epoch,
    )


def resume_sse_stream(
    prior: SessionBinding,
    last_event_id: str,
    token_resource: str,
    token_client_id: str,
    token_jti_lineage: str,
    token_subject: str,
    server_cursor_epoch: str,
) -> SessionBinding:
    try:
        return validate_resume(
            prior=prior,
            token_resource=token_resource,
            token_client_id=token_client_id,
            token_jti_lineage=token_jti_lineage,
            token_subject=token_subject,
            server_cursor_epoch=server_cursor_epoch,
        )
    except StreamRebindError:
        # Caller must discard last_event_id and re-initialize.
        raise StreamRebindError(
            f"refusing to resume with Last-Event-ID={last_event_id!r}; "
            f"tear down stream and re-initialize"
        )
