# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-sse-stream-after-a-server-initiated-elicitation-has-already-been-consumed-downstream.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-sse-stream-after-a-server-initiated-elicitation-has-already-been-consumed-downstream.warrant.json
# Markdown SHA-256:   3c3e31502f75ccf7508ab11756f80320511a9aece400e800207ae46593520bb8
# Code AST SHA-256:   427b95de1f7b8f8cfb95ea74bd60f92f240226058f0ef765fe3214b032b419a3
# Verified Classes:   ElicitationReplayDivergence, DurableCursor, ServerEventLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

Outcome = Literal["answered", "declined", "errored"]


class ElicitationReplayDivergence(RuntimeError):
    """Raised when SSE resumption would re-deliver an elicitation whose
    outcome is not durably recorded, or whose server-side resolution has
    been garbage-collected beneath the replay cursor."""


@dataclass
class DurableCursor:
    last_event_id: int
    # The elicitation ledger MUST live in the same durability domain as the
    # cursor. Persisting them separately opens the crash window that causes
    # duplicate approvals on replay.
    elicitation_outcomes: dict[str, Outcome] = field(default_factory=dict)

    def advance(self, new_event_id: int, elicitation_id: str | None, outcome: Outcome | None) -> None:
        if elicitation_id is not None:
            if outcome is None:
                raise ElicitationReplayDivergence(
                    f"advancing cursor past elicitation {elicitation_id} without an outcome"
                )
            self.elicitation_outcomes[elicitation_id] = outcome
        self.last_event_id = new_event_id


@dataclass
class ServerEventLog:
    events: list[dict]
    # Resolution records must be retained for >= event-log retention. If a
    # resolution is TTL'd out while its event is still replayable, resumption
    # produces an orphaned reference.
    resolved_elicitation_ttl_ticks: int
    event_log_retention_ticks: int

    def check_retention_invariant(self) -> None:
        if self.resolved_elicitation_ttl_ticks < self.event_log_retention_ticks:
            raise ElicitationReplayDivergence(
                "elicitation resolution retention "
                f"({self.resolved_elicitation_ttl_ticks}) shorter than event-log retention "
                f"({self.event_log_retention_ticks}); replays will orphan references"
            )


def resume_stream(
    client: DurableCursor,
    server: ServerEventLog,
    replay_from: int,
) -> list[dict]:
    """Replay events after a reconnect. Must short-circuit already-resolved
    elicitations via the client ledger rather than re-delivering them to the
    human gate."""
    server.check_retention_invariant()
    replayed = [e for e in server.events if e["id"] > replay_from]
    for event in replayed:
        if event.get("method") != "elicitation/create":
            continue
        eid = event["params"]["requestId"]
        if eid in client.elicitation_outcomes:
            # Short-circuit: do NOT re-prompt. The outcome is already committed.
            continue
        # No recorded outcome and no way to safely re-derive it: the client
        # would re-ask a question it may have already answered.
        raise ElicitationReplayDivergence(
            f"replay delivered elicitation {eid} with no durable outcome; "
            "re-prompting risks duplicate side effects"
        )
    return replayed


def handle_elicitation_result(
    server: ServerEventLog,
    request_id: str,
    outcome: Outcome,
    resolution_store: dict[str, Outcome],
) -> Outcome:
    """Idempotent on request_id. A duplicate POST returns the recorded outcome
    instead of re-executing or erroring."""
    if request_id in resolution_store:
        return resolution_store[request_id]
    if not any(
        e.get("method") == "elicitation/create" and e["params"]["requestId"] == request_id
        for e in server.events
    ):
        raise ElicitationReplayDivergence(
            f"elicitation result for unknown/expired request {request_id}"
        )
    resolution_store[request_id] = outcome
    return outcome
