# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prefetches-a-tool-call-under-a-stale-idempotency-key-and-the-reconciliation-ledger-cannot-distinguish-a-replay-from-a-ne.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prefetches-a-tool-call-under-a-stale-idempotency-key-and-the-reconciliation-ledger-cannot-distinguish-a-replay-from-a-ne.warrant.json
# Markdown SHA-256:   cb7d4d7b890189c3eaaefd798db7fd57096dd7e221bd16f69b66e68abb3cce74
# Code AST SHA-256:   bec02e97fdc621d53cae82d029779dce3bde55ec4753656110ed94588eaaa7ea
# Verified Classes:   IdempotencyCollisionError, LedgerState, LedgerEntry, ReconciliationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class IdempotencyCollisionError(RuntimeError):
    """Raised when a duplicate key cannot be proven to denote the same intent."""
    pass


class LedgerState(Enum):
    UNCONFIRMED = "unconfirmed"   # transmitted, no ack; execution unknown
    IN_FLIGHT = "in_flight"       # ack'd receipt, execution in progress
    CONFIRMED = "confirmed"       # terminal provider response recorded


@dataclass
class LedgerEntry:
    key: str
    epoch: int
    state: LedgerState
    last_heartbeat: float
    terminal_response: Optional[dict] = None


@dataclass
class ReconciliationLedger:
    entries: dict = field(default_factory=dict)
    provider_exec_window_s: float = 30.0

    def derive_key(self, plan_id: str, step_index: int, args: dict, epoch: int) -> str:
        # epoch is mandatory: it is the monotonic plan-version counter.
        material = f"{plan_id}|{step_index}|{epoch}|{sorted(args.items())}"
        return "spec:" + hashlib.sha256(material.encode()).hexdigest()[:24]

    def dispatch(self, key: str, epoch: int, current_epoch: int) -> dict:
        prior = self.entries.get(key)
        if prior is None:
            self.entries[key] = LedgerEntry(
                key=key, epoch=epoch, state=LedgerState.UNCONFIRMED,
                last_heartbeat=time.time(),
            )
            return {"action": "dispatch", "key": key}

        # Invariant: a key from a superseded epoch cannot be proven equivalent
        # to the current intent, even if the bytes match.
        if prior.epoch < current_epoch:
            raise IdempotencyCollisionError(
                f"key {key} minted at epoch {prior.epoch}, current plan epoch "
                f"{current_epoch}: dedup unsound, must reconcile against provider"
            )

        if prior.state is LedgerState.CONFIRMED:
            return {"action": "suppress", "key": key,
                    "response": prior.terminal_response}

        if prior.state is LedgerState.IN_FLIGHT:
            age = time.time() - prior.last_heartbeat
            if age <= self.provider_exec_window_s:
                return {"action": "suppress", "key": key, "reason": "in-flight"}
            raise IdempotencyCollisionError(
                f"key {key} in-flight {age:.1f}s > window "
                f"{self.provider_exec_window_s}s: execution status unknown"
            )

        # UNCONFIRMED: timeout is non-evidence of non-execution.
        raise IdempotencyCollisionError(
            f"key {key} is UNCONFIRMED: prior transmission may have executed; "
            f"probe provider ledger before re-dispatch"
        )

    def confirm(self, key: str, response: dict) -> None:
        entry = self.entries.get(key)
        if entry is None:
            raise IdempotencyCollisionError(f"confirm for unknown key {key}")
        entry.state = LedgerState.CONFIRMED
        entry.terminal_response = response
