# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reattaches-to-an-mcp-sse-stream-through-a-stateless-gateway-and-the-server-initiates-elicitation-mid-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reattaches-to-an-mcp-sse-stream-through-a-stateless-gateway-and-the-server-initiates-elicitation-mid-replay.warrant.json
# Markdown SHA-256:   b93b6fc69ddb033f2951c634c7c5a81355d9d4a9ba43291343224776245d457a
# Code AST SHA-256:   e617f15044efe6a92df651005c17cf8c9b5da4fa2b86b1a7c9c0126b9e34e8e4
# Verified Classes:   SplitBrainElicitationError, Elicitation, ReattachContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SplitBrainElicitationError(RuntimeError):
    """Raised when a client is asked to act on an elicitation it cannot
    prove it observed in the live stream, or when a response targets a
    pending-request table that does not contain the request id."""


@dataclass
class Elicitation:
    request_id: str
    observed_live: bool
    pending_on_instance: bool


@dataclass
class ReattachContext:
    last_event_id: int
    live_seen_ids: set = field(default_factory=set)
    pending_table: dict = field(default_factory=dict)  # id -> instance


def answer_elicitation(ctx: ReattachContext, elicit: Elicitation, response: dict) -> str:
    # Invariant 1: never answer an elicitation seen only in replay.
    if not elicit.observed_live and elicit.request_id not in ctx.live_seen_ids:
        raise SplitBrainElicitationError(
            f"elicitation {elicit.request_id} seen only in replay; "
            f"refusing to synthesize a response across stateless gateway"
        )
    # Invariant 2: the pending-request table on the receiving instance
    # must actually contain the request, or the response is orphaned.
    if elicit.request_id not in ctx.pending_table:
        raise SplitBrainElicitationError(
            f"elicitation {elicit.request_id} not pending on receiving instance; "
            f"response would be orphaned (split-brain elicitation)"
        )
    # Invariant 3: idempotent response keyed by request id, not instance.
    return hashlib.sha256(
        f"{elicit.request_id}:{sorted(response.items())}".encode()
    ).hexdigest()


def handle_reattach(ctx: ReattachContext, replayed: list) -> list:
    actions = []
    for ev in replayed:
        if ev.get("type") == "elicitation/create":
            el = Elicitation(
                request_id=ev["id"],
                observed_live=ev["id"] in ctx.live_seen_ids,
                pending_on_instance=ev["id"] in ctx.pending_table,
            )
            if not el.observed_live:
                # Force fresh re-issue rather than defaulting.
                actions.append(("reissue", el.request_id))
            else:
                actions.append(("answer", el.request_id))
    return actions
