# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-collapse-speculative-branches-when-a-reconciliation-quorum-is-reached-before-all-branch-witnesses-hav.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-collapse-speculative-branches-when-a-reconciliation-quorum-is-reached-before-all-branch-witnesses-hav.warrant.json
# Markdown SHA-256:   182e8d6e3ec770b4fbcc9111aa895f250ef51b50b38ee6502471095278a91047
# Code AST SHA-256:   ec317fa73ed8f5b043773b3ecee1964cc0595829880de806c3f25d36483036d1
# Verified Classes:   BranchState, ReconciliationInvariantError, Branch, Reconciliation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class BranchState(Enum):
    LAUNCHED = "launched"
    RUNNING = "running"
    SEALED_VERDICT = "sealed_verdict"
    SEALED_ABSTAIN = "sealed_abstain"
    UNSEALED_TIMEOUT = "unsealed_timeout"


class ReconciliationInvariantError(RuntimeError):
    """Raised when a collapse is attempted before all branch witnesses seal."""


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.LAUNCHED
    verdict: Optional[str] = None
    witness_hash: Optional[str] = None
    partial_tool_call: bool = False


@dataclass
class Reconciliation:
    launch_count: int
    quorum_threshold: int
    branches: Dict[str, Branch] = field(default_factory=dict)

    def register(self, branch_id: str) -> None:
        if branch_id in self.branches:
            raise ReconciliationInvariantError(f"duplicate branch {branch_id}")
        self.branches[branch_id] = Branch(branch_id)

    def seal(self, branch_id: str, verdict: Optional[str], transcript: str) -> None:
        b = self.branches[branch_id]
        if b.state in (BranchState.SEALED_VERDICT, BranchState.SEALED_ABSTAIN):
            raise ReconciliationInvariantError(f"{branch_id} already sealed")
        b.witness_hash = hashlib.sha256(transcript.encode()).hexdigest()
        if verdict is None:
            b.state = BranchState.SEALED_ABSTAIN
        else:
            b.state = BranchState.SEALED_VERDICT
            b.verdict = verdict

    def mark_unsealed_timeout(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        if b.partial_tool_call:
            # partial witnesses are provisional dissent, never abstentions
            b.state = BranchState.UNSEALED_TIMEOUT
        else:
            b.state = BranchState.UNSEALED_TIMEOUT

    def _sealed_count(self) -> int:
        return sum(
            1
            for b in self.branches.values()
            if b.state in (BranchState.SEALED_VERDICT, BranchState.SEALED_ABSTAIN)
        )

    def _quorum_satisfied(self) -> bool:
        # denominator is launch_count, never len(survivors)
        return self._sealed_count() >= self.quorum_threshold

    def _all_terminal(self) -> bool:
        terminal = {
            BranchState.SEALED_VERDICT,
            BranchState.SEALED_ABSTAIN,
            BranchState.UNSEALED_TIMEOUT,
        }
        return all(b.state in terminal for b in self.branches.values())

    def collapse(self) -> str:
        if not self._quorum_satisfied():
            raise ReconciliationInvariantError(
                f"quorum not met: {self._sealed_count()}/{self.quorum_threshold} "
                f"against launch_count={self.launch_count}"
            )
        if not self._all_terminal():
            unsealed = [
                b.branch_id
                for b in self.branches.values()
                if b.state not in (
                    BranchState.SEALED_VERDICT,
                    BranchState.SEALED_ABSTAIN,
                    BranchState.UNSEALED_TIMEOUT,
                )
            ]
            raise ReconciliationInvariantError(
                f"refusing collapse: unsealed branches {unsealed}; "
                f"drain-and-seal required before merge"
            )
        if len(self.branches) != self.launch_count:
            raise ReconciliationInvariantError(
                f"branch set drift: {len(self.branches)} registered vs "
                f"{self.launch_count} launched"
            )
        tally: Dict[str, int] = {}
        for b in self.branches.values():
            if b.state == BranchState.SEALED_VERDICT and b.verdict:
                tally[b.verdict] = tally.get(b.verdict, 0) + 1
        if not tally:
            raise ReconciliationInvariantError("no sealed verdicts to merge")
        winner = max(tally, key=tally.get)
        return winner
