# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-against-a-server-that-has-silently-rotated-its-session-identity-the-mcp-session-id-resurrection-t.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-against-a-server-that-has-silently-rotated-its-session-identity-the-mcp-session-id-resurrection-t.warrant.json
# Markdown SHA-256:   746b5234dd6bc19a8ff363923f1e237abf41cae5e4987f49f9d043a11a2ed683
# Code AST SHA-256:   16a8b6128b984af1bbc1b988bb2fb95a8137853e65f9c2d42fffba33c310da61
# Verified Classes:   SessionResumeError, ResumeState, SessionHandle, ResumeContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SessionResumeError(RuntimeError):
    """Raised when a resuming agent cannot safely classify a stale session id."""


class ResumeState(enum.Enum):
    RESUMED = "resumed"          # session id accepted, stream continuity intact
    FORKED = "forked"            # id rejected, re-initialized, obligations unknown
    ABANDONED = "abandoned"      # id rejected, obligations explicitly given up


@dataclass
class SessionHandle:
    session_id: str
    last_event_id: Optional[str]
    pending_obligations: set[str] = field(default_factory=set)  # non-idempotent or server-held


@dataclass
class ResumeContext:
    handle: SessionHandle
    state: ResumeState = ResumeState.RESUMED
    event_history_continuous: bool = True


def resume_session(
    stored: SessionHandle,
    server_accepts: bool,
    new_session_id: Optional[str] = None,
) -> ResumeContext:
    """
    Classify a resume attempt. `server_accepts` is the result of the
    first request bearing the stored session id (True if 2xx, False if 404).
    """
    if server_accepts:
        return ResumeContext(handle=stored, state=ResumeState.RESUMED)

    # Server rejected the id. Per spec this may mean expired OR rotated.
    # We must NOT silently re-initialize if obligations are outstanding.
    if not new_session_id:
        raise SessionResumeError(
            f"cannot classify rejection of session {stored.session_id!r}: "
            "no replacement id supplied; refusing to fork blind"
        )

    forked = SessionHandle(
        session_id=new_session_id,
        last_event_id=None,  # MUST clear: old stream id belongs to dead session
        pending_obligations=set(stored.pending_obligations),
    )
    ctx = ResumeContext(
        handle=forked,
        state=ResumeState.FORKED,
        event_history_continuous=False,
    )

    if stored.pending_obligations:
        # Fork with outstanding obligations is unsafe to proceed from.
        # Surface it so the reasoning loop must reconcile or abandon.
        raise SessionResumeError(
            f"session {stored.session_id!r} forked to {new_session_id!r} with "
            f"unreconciled obligations {sorted(stored.pending_obligations)}; "
            "event history is discontinuous — resync required before non-idempotent calls"
        )
    return ctx


def guard_non_idempotent(ctx: ResumeContext, op_fingerprint: str) -> None:
    """Gate: refuse non-idempotent work from a forked session without resync."""
    if ctx.state is ResumeState.FORKED and not ctx.event_history_continuous:
        raise SessionResumeError(
            f"refusing non-idempotent op {op_fingerprint!r} on forked session "
            f"{ctx.handle.session_id!r}: continuity not re-established"
        )
