# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-attestation-quorums-when-byzantine-agent-auditors-sign-divergent-result-hashes-for-the-same-task-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-attestation-quorums-when-byzantine-agent-auditors-sign-divergent-result-hashes-for-the-same-task-epoch.warrant.json
# Markdown SHA-256:   0b29067f4cba22fa5440650adf3b9fe4b28a3ae7949ef84e7b7285eea7eaefe8
# Code AST SHA-256:   364c7eb9b2cbc1cc38d4da900f730033021dce075c39f49c5c25c152be304120
# Verified Classes:   AttestationEquivocationError, CanonicalizationMismatchError, SignedAttestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Iterable


class AttestationEquivocationError(RuntimeError):
    """Raised when a quorum's signatures cannot be reconciled to one semantic digest."""


class CanonicalizationMismatchError(RuntimeError):
    """Raised when a minority signature's raw artifact does not replay to the majority digest."""


@dataclass(frozen=True)
class SignedAttestation:
    auditor_id: str
    schema_version: str
    canonical_digest: str
    raw_artifact: dict


def canonicalize(artifact: dict, schema_version: str) -> str:
    # Pinned canonicalizer: sorted keys, no trailing whitespace, fixed float format.
    normalized = json.dumps(
        artifact, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    ).strip()
    return hashlib.sha256(f"{schema_version}|{normalized}".encode()).hexdigest()


def settle_quorum(
    attestations: Iterable[SignedAttestation],
    f: int,
    schema_version: str,
) -> str:
    sigs = list(attestations)
    quorum = 2 * f + 1
    if len(sigs) < quorum:
        raise AttestationEquivocationError(
            f"insufficient signatures: {len(sigs)} < quorum {quorum}"
        )

    groups: dict[str, list[SignedAttestation]] = {}
    for s in sigs:
        if s.schema_version != schema_version:
            raise CanonicalizationMismatchError(
                f"auditor {s.auditor_id} signed under schema {s.schema_version}, "
                f"coordinator pinned {schema_version}"
            )
        groups.setdefault(s.canonical_digest, []).append(s)

    # Majority digest must itself reach f+1 to prove honest endorsement.
    majority_digest, majority = max(groups.items(), key=lambda kv: len(kv[1]))
    if len(majority) < f + 1:
        raise AttestationEquivocationError(
            f"no digest reached f+1={f + 1}; top group has {len(majority)}"
        )

    # Replay minority signatures through the pinned canonicalizer.
    for digest, minority in groups.items():
        if digest == majority_digest:
            continue
        for s in minority:
            replayed = canonicalize(s.raw_artifact, schema_version)
            if replayed != majority_digest:
                raise AttestationEquivocationError(
                    f"semantic divergence: auditor {s.auditor_id} replayed to "
                    f"{replayed}, not majority {majority_digest} — Byzantine fault"
                )
            # If replay matches majority, divergence was representational: safe.

    return majority_digest
