# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-invalid-when-a-server-push-elicitation-was-in-flight-during-tra.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-http-session-resumption-as-invalid-when-a-server-push-elicitation-was-in-flight-during-tra.warrant.json
# Markdown SHA-256:   9a300e7abebec29600196c8d4540979c493ea2b8d3deaa5dfa6951dba4ee2f91
# Code AST SHA-256:   821b7619ec7c40bd3595a75cfde0844894dbb307dc475ce267a863a67b742102
# Verified Classes:   ElicitationResumptionError, ElicitationState, ElicitationRecord, SessionCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ElicitationResumptionError(RuntimeError):
    """Raised when a replayed elicitation cannot be proven live-or-dead."""


class ElicitationState(Enum):
    PENDING = "pending"
    ANSWERED = "answered"
    CANCELLED = "cancelled"


@dataclass
class ElicitationRecord:
    request_id: str
    state: ElicitationState
    response: dict | None = None


@dataclass
class SessionCursor:
    last_event_id: str
    answered: dict[str, ElicitationRecord] = field(default_factory=dict)

    def persist_atomic(self, event_id: str, record: ElicitationRecord) -> None:
        # Cursor advance and answer record must be one transaction.
        self.answered[record.request_id] = record
        self.last_event_id = event_id


def handle_replayed_elicitation(
    cursor: SessionCursor,
    replayed_event_id: str,
    replayed_request_id: str,
    server_retains_handler: bool,
) -> str:
    prior = cursor.answered.get(replayed_request_id)

    if prior is not None and prior.state is ElicitationState.ANSWERED:
        # Same request id, already answered: do NOT re-answer.
        if not server_retains_handler:
            # Server has no live handler; the replay is a zombie.
            raise ElicitationResumptionError(
                f"Zombie elicitation {replayed_request_id!r} replayed on "
                f"event {replayed_event_id!r} but server retains no handler; "
                "session must be abandoned, not resumed."
            )
        return "noop_reacknowledge"

    if prior is not None and prior.state is ElicitationState.CANCELLED:
        raise ElicitationResumptionError(
            f"Elicitation {replayed_request_id!r} was cancelled but was "
            f"replayed on event {replayed_event_id!r}; refusing to answer."
        )

    if not server_retains_handler:
        # First sighting but server says handler is gone: dead elicitation.
        raise ElicitationResumptionError(
            f"Elicitation {replayed_request_id!r} at event {replayed_event_id!r} "
            "has no live server handler; cannot treat as answerable."
        )

    return "answer_once"


def dedup_key(request_id: str, payload: dict) -> str:
    # Dedup MUST key on request_id, never on payload hash.
    return request_id  # payload intentionally ignored
