# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocating-result-attestations-as-a-first-class-byzantine-fault-rather-than-a-transient-inconsistency.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocating-result-attestations-as-a-first-class-byzantine-fault-rather-than-a-transient-inconsistency.warrant.json
# Markdown SHA-256:   681988cb73b64749bb3d0555668c638cdaf8f72872a2f32f68624ab7830244f6
# Code AST SHA-256:   727d7bbceb646bfa25901a8dbba62dbacf453aefad1764361339d3b1144d4233
# Verified Classes:   EquivocationDetected, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when one identity signs two conflicting attestations for the same (task, epoch)."""
    pass


@dataclass(frozen=True)
class Attestation:
    agent_id: str
    task_id: str
    epoch: int
    result_hash: str
    signature: str  # signature over (task_id, epoch, result_hash)


def _signed_payload(att: Attestation) -> str:
    return f"{att.task_id}|{att.epoch}|{att.result_hash}"


def verify_signature(att: Attestation) -> bool:
    # Placeholder for real Ed25519 verification over _signed_payload(att).
    return att.signature == hashlib.sha256(_signed_payload(att).encode()).hexdigest()


def check_equivocation(incoming: Attestation, history: list[Attestation]) -> None:
    """
    Pre-resolution guard. Must run BEFORE any timestamp/majority conflict logic.
    Raises EquivocationDetected if the same identity signed a different result
    for the same (task_id, epoch).
    """
    if not verify_signature(incoming):
        raise EquivocationDetected(
            f"invalid signature from {incoming.agent_id} on {incoming.task_id}@{incoming.epoch}"
        )
    for prior in history:
        if (
            prior.agent_id == incoming.agent_id
            and prior.task_id == incoming.task_id
            and prior.epoch == incoming.epoch
            and prior.result_hash != incoming.result_hash
        ):
            raise EquivocationDetected(
                f"equivocation by {incoming.agent_id} on {incoming.task_id}@{incoming.epoch}: "
                f"{prior.result_hash[:12]} vs {incoming.result_hash[:12]}"
            )


def assemble_quorum(attestations: list[Attestation], quorum_size: int = 3) -> str:
    history: list[Attestation] = []
    for att in attestations:
        check_equivocation(att, history)  # hard gate, never skipped
        history.append(att)
    # Only reachable if no equivocation was found; group by result hash.
    by_result: dict[str, int] = {}
    for att in history:
        by_result[att.result_hash] = by_result.get(att.result_hash, 0) + 1
    winner = max(by_result, key=by_result.get)
    if by_result[winner] < quorum_size:
        raise EquivocationDetected("no quorum reached without equivocation")
    return winner
