# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-equivocation-in-multi-agent-result-commitment-quorums-before-finality-is-reached.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-equivocation-in-multi-agent-result-commitment-quorums-before-finality-is-reached.warrant.json
# Markdown SHA-256:   1582896475c14337e6af9979d6310f64af2d46b2b5bfdf28147228cdbc39d154
# Code AST SHA-256:   d928e2ebaabfa6bda67557ec7a449267a24679046018a2c3b721bea7a3d18d2f
# Verified Classes:   EquivocationDetected, SignedVote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from collections import defaultdict
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when an agent signed conflicting votes for the same task epoch."""


@dataclass(frozen=True)
class SignedVote:
    task_id: str
    epoch: int
    agent_id: str
    result: str          # e.g. "APPROVE" / "REJECT"
    signature: bytes     # sig over (task_id, epoch, agent_id, result)

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(f"{self.task_id}|{self.epoch}|{self.agent_id}|{self.result}".encode())
        return h.hexdigest()


def finalize_epoch(
    votes: list[SignedVote],
    *,
    task_id: str,
    epoch: int,
    n_agents: int,
    f: int,
) -> str:
    """
    Dedup-by-agent, detect equivocation, THEN count.
    Never count before dedup: a raw 2f+1 count over a multiset with a
    duplicated agent can certify two disjoint quorums.
    """
    quorum = 2 * f + 1
    by_agent: dict[str, set[str]] = defaultdict(set)

    for v in votes:
        if v.task_id != task_id or v.epoch != epoch:
            continue
        by_agent[v.agent_id].add(v.result)

    # Structural signal: an agent with >1 distinct result in one epoch.
    equivocators = {a for a, results in by_agent.items() if len(results) > 1}
    if equivocators:
        # Cannot safely finalize: the count is now unreliable.
        raise EquivocationDetected(
            f"epoch {epoch} of {task_id}: agents {sorted(equivocators)} "
            f"emitted conflicting signed votes; invalidate epoch and "
            f"quarantine before recount"
        )

    # Clean path: one result per agent, now the threshold is meaningful.
    tally: dict[str, int] = defaultdict(int)
    for agent, results in by_agent.items():
        (result,) = results
        tally[result] += 1

    winners = [r for r, c in tally.items() if c >= quorum]
    if len(winners) != 1:
        raise EquivocationDetected(
            f"epoch {epoch} of {task_id}: no unique quorum "
            f"(tally={dict(tally)}, quorum={quorum}); refuse finality"
        )
    return winners[0]
