# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-pre-executes-speculative-tool-calls-under-a-shared-idempotency-key-and-the-effect-ledger-reconciles-against-the-wrong-br.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-pre-executes-speculative-tool-calls-under-a-shared-idempotency-key-and-the-effect-ledger-reconciles-against-the-wrong-br.warrant.json
# Markdown SHA-256:   e521ac3a212294795098166e2085e7b01c86c77f9a7c1257c0be58671406e9ae
# Code AST SHA-256:   815853b4f0b44be2eb5443b8cfef0d94b3a2e2f6573b86415ff3603eca6734a3
# Verified Classes:   SpeculativeWindowViolation, EffectState, SpeculativeEffect, SpeculativeWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class SpeculativeWindowViolation(RuntimeError):
    """Raised when a speculative effect cannot be attributed to a committed branch."""


class EffectState(Enum):
    OPEN = "open"
    SETTLED = "settled"
    RELEASED = "released"
    ORPHANED = "orphaned"


@dataclass
class SpeculativeEffect:
    branch: str
    idempotency_key: str
    transaction_id: Optional[str]
    state: EffectState = EffectState.OPEN
    amount: int = 0


@dataclass
class SpeculativeWindow:
    committed_branch: Optional[str] = None
    effects: Dict[str, SpeculativeEffect] = field(default_factory=dict)

    def pre_execute(self, branch: str, amount: int) -> str:
        key = hashlib.sha256(f"{branch}:{amount}".encode()).hexdigest()[:16]
        self.effects[key] = SpeculativeEffect(
            branch=branch, idempotency_key=key, transaction_id=None, amount=amount
        )
        return key

    def record_effect(self, key: str, transaction_id: str) -> None:
        self.effects[key].transaction_id = transaction_id
        self.effects[key].state = EffectState.OPEN

    def commit(self, branch: str) -> None:
        self.committed_branch = branch

    def close_window(self) -> List[str]:
        """Terminalize all effects. Returns keys that could not be safely resolved."""
        if self.committed_branch is None:
            raise SpeculativeWindowViolation("window closed before branch commit")
        unresolved: List[str] = []
        for key, eff in self.effects.items():
            if eff.branch == self.committed_branch:
                if eff.state == EffectState.OPEN:
                    eff.state = EffectState.SETTLED
            else:
                if eff.state == EffectState.OPEN and eff.transaction_id is None:
                    eff.state = EffectState.RELEASED
                elif eff.state == EffectState.OPEN and eff.transaction_id is not None:
                    # irreversible effect on an abandoned branch
                    eff.state = EffectState.ORPHANED
                    unresolved.append(key)
        return unresolved

    def reconcile(self) -> int:
        """Sum effects that the ledger will treat as authoritative."""
        orphans = [k for k, e in self.effects.items() if e.state == EffectState.ORPHANED]
        if orphans:
            raise SpeculativeWindowViolation(
                f"orphaned speculative effects on abandoned branches: {orphans}"
            )
        settled = sum(
            e.amount for e in self.effects.values() if e.state == EffectState.SETTLED
        )
        return settled


def run_refund_plan(window: SpeculativeWindow) -> int:
    # Agent speculates both branches before committing.
    full_key = window.pre_execute("refund_full", 100)
    partial_key = window.pre_execute("refund_partial", 50)

    # Partial branch lands first; full branch is rate-limited at first attempt.
    window.record_effect(partial_key, transaction_id="tx_partial_1")
    # Full branch retries under its own key and lands.
    window.record_effect(full_key, transaction_id="tx_full_1")

    # Reasoning converges on full refund.
    window.commit("refund_full")

    unresolved = window.close_window()
    if unresolved:
        # Without a compensation handle, the partial refund is an orphan.
        raise SpeculativeWindowViolation(
            "abandoned branch produced irreversible effect; capture "
            "transaction_id at speculation time to enable compensation"
        )
    return window.reconcile()
