# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-federated-byzantine-quorum-slices-from-silently-collapsing-under-non-deterministic-agent-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-federated-byzantine-quorum-slices-from-silently-collapsing-under-non-deterministic-agent-outputs.warrant.json
# Markdown SHA-256:   ee786de2a6ef52384f8626ff897e17d7f017aa7bb9d07a17d42e75f7c54ebbb8
# Code AST SHA-256:   58cee3c5a7c3f1cf37f8d78264b588f5c5fbd375de274cc0901454907cfac0cb
# Verified Classes:   CanonicalizationError, SemanticDriftError, Verdict, Ballot
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import FrozenSet


class CanonicalizationError(RuntimeError):
    """Raised when an agent output cannot be mapped to the finite verdict set."""


class SemanticDriftError(RuntimeError):
    """Raised when committed ballots disagree on canonical value identity."""


class Verdict(str, Enum):
    PASS = "PASS"
    FAIL = "FAIL"
    ABSTAIN = "ABSTAIN"
    UNKNOWN = "UNKNOWN"


CANONICALIZER_VERSION = "verdict-set-v3"


@dataclass(frozen=True)
class Ballot:
    node_id: str
    verdict: Verdict
    canonicalizer_version: str

    def identity(self) -> tuple[str, str]:
        # Ballot identity includes the canonicalizer version: a node running a
        # different canonicalizer is voting on a different value domain.
        return (self.verdict.value, self.canonicalizer_version)


_ALLOWED = {
    "pass": Verdict.PASS, "true": Verdict.PASS, "yes": Verdict.PASS,
    "fail": Verdict.FAIL, "false": Verdict.FAIL, "no": Verdict.FAIL,
    "uncertain": Verdict.ABSTAIN, "unknown": Verdict.ABSTAIN,
}


def canonicalize(raw: str) -> Verdict:
    key = raw.strip().strip('"').lower()
    if key not in _ALLOWED:
        raise CanonicalizationError(
            f"agent output {raw!r} not in verdict set {CANONICALIZER_VERSION}; "
            "refuse rather than fuzzy-match"
        )
    return _ALLOWED[key]


def check_quorum_consistency(ballots: list[Ballot]) -> Verdict:
    """Enforce the payload canonicalization invariant across a quorum.

    The FBA intersection proof guarantees shared *nodes*; this function
    guarantees shared *value identity* over those nodes. Without it, a quorum
    can commit with matching vote digests but divergent semantics.
    """
    if not ballots:
        raise SemanticDriftError("empty quorum")
    versions = {b.canonicalizer_version for b in ballots}
    if len(versions) > 1:
        raise SemanticDriftError(
            f"quorum spans canonicalizer versions {versions}; "
            "intersection guarantee does not apply across value domains"
        )
    identities = {b.identity() for b in ballots}
    if len(identities) > 1:
        raise SemanticDriftError(
            f"quorum committed divergent value identities {identities}"
        )
    verdicts = {b.verdict for b in ballots}
    # Abstention must be tolerated, not treated as absence.
    if Verdict.ABSTAIN in verdicts and len(verdicts) > 1:
        raise SemanticDriftError(
            "mixed ABSTAIN and definite verdicts require explicit "
            "abstention-tolerant slice configuration"
        )
    return next(iter(verdicts))


def commit(ballots: list[Ballot], slice_size: int, threshold: int) -> Verdict:
    if len(ballots) < slice_size:
        raise SemanticDriftError(
            f"slice under-filled: {len(ballots)}/{slice_size}"
        )
    definite = [b for b in ballots if b.verdict is not Verdict.ABSTAIN]
    if len(definite) < threshold:
        raise SemanticDriftError(
            f"insufficient definite votes {len(definite)}/{threshold}; "
            "abstention tolerance exhausted"
        )
    return check_quorum_consistency(definite)
