# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-irreversible-tool-effects-poisoning-merge-time-reconciliation-in-branch-and-merge-plan-trees.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-irreversible-tool-effects-poisoning-merge-time-reconciliation-in-branch-and-merge-plan-trees.warrant.json
# Markdown SHA-256:   9d41b579c1bf0d1e8eb46caacd48d2c701e48a8df5ff3a07fcbb600e0fc2d8ca
# Code AST SHA-256:   37946e478c6e53c0fd4e82c18a5a2dc039e047387d64ebeb0ae2a591c3b3f27a
# Verified Classes:   BranchStatus, MergeInvariantViolation, EffectReservation, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class BranchStatus(Enum):
    SUCCEEDED = "succeeded"
    FAILED_PRE_EFFECT = "failed_pre_effect"
    FAILED_POST_EFFECT_UNCONFIRMED = "failed_post_effect_unconfirmed"
    ABORTED_BY_PLANNER = "aborted_by_planner"


class MergeInvariantViolation(RuntimeError):
    """Raised when a merge would proceed over an uncompensated orphan effect."""


@dataclass(frozen=True)
class EffectReservation:
    branch_id: str
    idempotency_key: str
    descriptor: str
    confirmed: bool


@dataclass
class Branch:
    branch_id: str
    status: BranchStatus
    reservations: list[EffectReservation] = field(default_factory=list)


def reconcile_merge(
    branches: Iterable[Branch],
    selected_branch_id: str,
    external_effect_log: dict[str, int],
) -> dict[str, int]:
    """Compute the effect set of the merged plan.

    Invariant: the merged effect set must contain exactly one confirmed
    emission per idempotency_key, and every orphaned reservation must be
    compensated before the merge is declared sound.
    """
    branches = list(branches)
    selected = {b.branch_id: b for b in branches}.get(selected_branch_id)
    if selected is None:
        raise MergeInvariantViolation(
            f"selected branch {selected_branch_id!r} not present in tree"
        )

    merged: dict[str, int] = {}
    orphans: list[EffectReservation] = []

    for branch in branches:
        for res in branch.reservations:
            if branch.branch_id == selected_branch_id:
                merged[res.idempotency_key] = merged.get(res.idempotency_key, 0) + 1
            elif not res.confirmed:
                # Effect emitted, confirmation never reached: orphan.
                orphans.append(res)
            # Confirmed non-selected emissions are presumed compensated by
            # the branch's own rollback; the reconciler must verify below.

    if orphans:
        raise MergeInvariantViolation(
            "discard path encountered post-effect unconfirmed reservations; "
            f"compensate before merge: {[(o.branch_id, o.idempotency_key) for o in orphans]}"
        )

    for key, count in merged.items():
        if count > 1:
            raise MergeInvariantViolation(
                f"duplicate emission for idempotency_key {key!r}: "
                f"merged plan would emit {count} times"
            )
        if external_effect_log.get(key, 0) > count:
            raise MergeInvariantViolation(
                f"external log shows {external_effect_log[key]} emissions for {key!r} "
                f"but merged plan accounts for {count}; orphan effect detected"
            )

    return merged
