# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-fork-branches-when-cost-aware-pruning-discards-the-branch-that-consensus-later-proves-correct.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-fork-branches-when-cost-aware-pruning-discards-the-branch-that-consensus-later-proves-correct.warrant.json
# Markdown SHA-256:   cfcaee4ffe27c5b5961e916555caa982b12943e374ba08e0541cb59cffca1907
# Code AST SHA-256:   032e71b14f7d2198ba6e95879ec7df3af5f5f20f08fdc109c1a130348265b999
# Verified Classes:   Reversibility, Branch, AuditCitation, MergeInadmissibleError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class Reversibility(Enum):
    RECONSTRUCTIBLE = "reconstructible"
    RESUMABLE = "resumable"
    LOST = "lost"


@dataclass
class Branch:
    branch_id: str
    reversibility: Reversibility
    pruned: bool
    replay_path: Optional[str] = None  # required if RECONSTRUCTIBLE


@dataclass
class AuditCitation:
    auditor_id: str
    cited_branch_id: str
    contradicts_survivors: bool


class MergeInadmissibleError(RuntimeError):
    """Raised when consensus would certify a plan whose contradicting
    evidence points at a branch that pruning made unrecoverable."""


def check_merge_admissibility(
    branches: dict[str, Branch],
    citations: list[AuditCitation],
    survivor_ids: set[str],
) -> None:
    for cite in citations:
        if not cite.contradicts_survivors:
            continue
        b = branches.get(cite.cited_branch_id)
        if b is None:
            raise MergeInadmissibleError(
                f"auditor {cite.auditor_id} cites unknown branch "
                f"{cite.cited_branch_id}; merge pool is incomplete"
            )
        if b.branch_id in survivor_ids:
            continue  # already representable in the vote
        if b.reversibility is Reversibility.RECONSTRUCTIBLE:
            if b.replay_path is None:
                raise MergeInadmissibleError(
                    f"branch {b.branch_id} tagged RECONSTRUCTIBLE but has no "
                    f"replay path; cannot re-instantiate into merge pool"
                )
            continue  # recoverable: re-instantiate before tallying
        if b.reversibility is Reversibility.RESUMABLE:
            continue  # recoverable via checkpoint
        # LOST and cited as contradicting evidence -> cannot certify
        raise MergeInadmissibleError(
            f"merge tainted: auditor {cite.auditor_id} contradicts survivors "
            f"using pruned branch {b.branch_id}, which is LOST. Refuse to "
            f"certify; emit re-plan directive charged to pruning reserve."
        )


def tally_consensus(
    branches: dict[str, Branch],
    citations: list[AuditCitation],
    survivor_ids: set[str],
    votes: dict[str, str],
) -> str:
    # Admissibility gate runs BEFORE the vote is read.
    check_merge_admissibility(branches, citations, survivor_ids)
    if not votes:
        raise MergeInadmissibleError("no auditor votes recorded")
    winner, count = max(
        ((k, list(votes.values()).count(k)) for k in set(votes.values())),
        key=lambda kv: kv[1],
    )
    return winner
