# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-replay-as-invalid-against-a-re-bound-oauth-2-1-resource-token.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-replay-as-invalid-against-a-re-bound-oauth-2-1-resource-token.warrant.json
# Markdown SHA-256:   c44050fa65b4747f1b28a16ea9ba4c349ca8a899ca3bc4349923555346ab6c3f
# Code AST SHA-256:   28d48e51c2531835db4075962400a78698016e60cefa2649959dbaa4707a39e4
# Verified Classes:   ResumptionBindingError, SessionRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ResumptionBindingError(RuntimeError):
    """Raised when an SSE resumption cursor and the presenting token
    were minted under different principals or audiences."""


@dataclass
class SessionRecord:
    session_id: str
    bound_sub: str
    bound_aud: str
    bound_jti_hash: str
    replay_epoch: int = 0
    # events: list of (event_id, required_scope, payload, minted_under_sub)
    events: list = field(default_factory=list)


def _jti_hash(token: dict) -> str:
    return hashlib.sha256(token["jti"].encode()).hexdigest()


def validate_resumption(
    session: SessionRecord,
    token: dict,
    last_event_id: int,
    required_scope_check,
) -> list:
    """
    Returns the filtered list of events eligible for replay.
    Raises ResumptionBindingError on principal/audience mismatch.
    """
    if token.get("aud") != session.bound_aud:
        raise ResumptionBindingError(
            f"aud mismatch: token aud={token.get('aud')!r} "
            f"session aud={session.bound_aud!r}"
        )

    if token.get("sub") != session.bound_sub:
        # Delegation / baton-pass / confused-deputy: never replay across principals.
        session.replay_epoch += 1
        session.events.clear()
        raise ResumptionBindingError(
            f"principal mismatch: token sub={token.get('sub')!r} "
            f"session sub={session.bound_sub!r}; session buffer invalidated"
        )

    if last_event_id < 0 or last_event_id > len(session.events):
        raise ResumptionBindingError(
            f"cursor {last_event_id} out of range for session "
            f"{session.session_id} (len={len(session.events)})"
        )

    eligible = []
    for event_id, required_scope, payload, minted_under in session.events:
        if event_id <= last_event_id:
            continue
        if minted_under != token["sub"]:
            # Defensive: even with same sub, reject events minted under a
            # different principal (e.g. after a prior epoch bump).
            raise ResumptionBindingError(
                f"event {event_id} minted under {minted_under!r}, "
                f"token sub={token['sub']!r}"
            )
        if not required_scope_check(token.get("scope", ""), required_scope):
            # Scope narrowed relative to mint time: drop, do not replay.
            continue
        eligible.append((event_id, payload))
    return eligible
