# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-http-mcp-session-after-the-server-has-reaped-it-silent-scope-widening-at-the-sse-last-event-id-boun.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-a-streamable-http-mcp-session-after-the-server-has-reaped-it-silent-scope-widening-at-the-sse-last-event-id-boun.warrant.json
# Markdown SHA-256:   4daa70061dddad669b8a3bde5c6baf30357cbe8c37f2aff8c081ace80ec1f2c5
# Code AST SHA-256:   698e37aa8302ff4b7b86c2adebb7d291230ef0af286f1342dbabeae0e102c714
# Verified Classes:   ScopeContinuityViolation, SessionState, PlanWarrant, ResumableSessionGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Callable


class ScopeContinuityViolation(RuntimeError):
    """Raised when a resumed MCP session's effective scopes diverge from the
    scopes the in-flight plan was built against, or when a denied narrow-scope
    tool would fall back to a broader-scope tool without an explicit warrant."""


@dataclass
class SessionState:
    session_id: str
    last_event_id: int
    scopes: frozenset[str]
    suspended_at: float | None = None
    capability_model_generation: int = 0


@dataclass
class PlanWarrant:
    """The scopes the current plan was authorized to rely on, frozen at plan time."""
    required_scopes: frozenset[str]
    permitted_fallbacks: dict[str, str] = field(default_factory=dict)  # denied_tool -> fallback_tool


class ResumableSessionGuard:
    """Bounds the Last-Event-ID resume seam for streamable-HTTP MCP sessions."""

    SCOPE_CLASS_RANK = {"tools:read": 0, "repo:write": 1, "deploy:trigger": 2}

    def __init__(
        self,
        introspect_scopes: Callable[[str], frozenset[str]],
        now: Callable[[], float] = time.monotonic,
    ) -> None:
        self._introspect = introspect_scopes
        self._now = now

    def on_suspend(self, state: SessionState) -> None:
        state.suspended_at = self._now()

    def on_resume(
        self,
        state: SessionState,
        presented_last_event_id: int,
        warrant: PlanWarrant,
    ) -> SessionState:
        # Step 1: transport-level resume is assumed to have succeeded upstream.
        # We do NOT trust that as an authorization event.
        if presented_last_event_id > state.last_event_id:
            raise ScopeContinuityViolation(
                f"resume Last-Event-ID {presented_last_event_id} ahead of known "
                f"{state.last_event_id}; server log rotated, continuity unprovable"
            )

        # Step 2: mandatory re-derivation of effective scopes across the seam.
        effective = self._introspect(state.session_id)

        # Step 3: fail closed if the plan's required scopes are no longer held.
        missing = warrant.required_scopes - effective
        if missing:
            raise ScopeContinuityViolation(
                f"session {state.session_id} resumed with narrowed scopes; "
                f"plan requires {sorted(missing)} but grant no longer holds them. "
                f"Re-negotiate before issuing further tools/call frames."
            )

        state.scopes = effective
        state.last_event_id = presented_last_event_id
        state.suspended_at = None
        state.capability_model_generation += 1
        return state

    def classify_inband_error(self, state: SessionState, error_code: str) -> str:
        # In-band JSON-RPC errors on a 200-OK SSE stream must be reclassified.
        if error_code == "insufficient_scope":
            return "authorization"  # route to renegotiation, NOT retry
        return "tool"

    def authorize_fallback(
        self,
        state: SessionState,
        denied_tool: str,
        proposed_fallback: str,
        warrant: PlanWarrant,
    ) -> None:
        if proposed_fallback not in state.scopes:
            raise ScopeContinuityViolation(
                f"fallback {proposed_fallback} not in held scopes {sorted(state.scopes)}"
            )
        # Block silent widening: a denied narrow tool may not fall back to a
        # broader-scope tool unless the fallback was pre-declared in the warrant.
        denied_rank = self.SCOPE_CLASS_RANK.get(denied_tool, -1)
        fallback_rank = self.SCOPE_CLASS_RANK.get(proposed_fallback, -1)
        if fallback_rank > denied_rank:
            if warrant.permitted_fallbacks.get(denied_tool) != proposed_fallback:
                raise ScopeContinuityViolation(
                    f"unauthorized scope-widening fallback: {denied_tool} "
                    f"(rank {denied_rank}) -> {proposed_fallback} (rank {fallback_rank}); "
                    f"not declared in plan warrant. Escalate to operator."
                )
