# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-withhold-its-own-attestation-equivocation-detection-deadlock-at-the-f-1-quorum-boundary-in-agent-result-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-withhold-its-own-attestation-equivocation-detection-deadlock-at-the-f-1-quorum-boundary-in-agent-result-commitment.warrant.json
# Markdown SHA-256:   f7a31755bc5ecfd65be7e6e94d1ea1035a5ec8e6e5020c21ebf47fdaaa7491f9
# Code AST SHA-256:   058e04850d49cd664ea99f3d1dc7e5697272234e37a1a36ff01548b00556aba7
# Verified Classes:   AttestationError, VoteKind, Attestation, ConflictObservation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class AttestationError(RuntimeError):
    """Raised when an instance's attestation decision violates the BFT abstain invariant."""
    pass


class VoteKind(Enum):
    FOR = "for"
    ABSTAIN_AGAINST = "abstain_against"  # counted as negative vote, carries evidence
    ABSENT = "absent"                     # silence; NOT counted


@dataclass(frozen=True)
class Attestation:
    signer: str
    task_id: str
    epoch: int
    value: str
    timestamp: int


@dataclass
class ConflictObservation:
    first: Attestation
    second: Attestation
    accused_candidates: tuple  # both signers, unattributable at local boundary


def decide_attestation(
    self_id: str,
    task_id: str,
    epoch: int,
    my_value: str,
    observed: list[Attestation],
    fault_proofs: dict,  # accused -> count of matching f+1 proofs
    f: int,
) -> tuple[VoteKind, Optional[ConflictObservation]]:
    """
    Implements the decision boundary: local conflict -> ABSTAIN with evidence;
    aggregated conflict (f+1 proofs) -> vote normally against slashed signer.
    Silent withholding (ABSENT) on a detected conflict is the deadlock bug.
    """
    # Group by value; detect conflicting values for same (task, epoch)
    by_value: dict[str, list[Attestation]] = {}
    for a in observed:
        if a.task_id == task_id and a.epoch == epoch:
            by_value.setdefault(a.value, []).append(a)

    if len(by_value) <= 1:
        # No conflict observed; vote for my_value.
        return VoteKind.FOR, None

    # Conflict observed. Can we attribute it?
    for accused, count in fault_proofs.items():
        if count >= f + 1:
            # Attribution complete: vote normally, slashed signer excluded.
            return VoteKind.FOR, None

    # Local conflict, unattributable. MUST emit evidence-bearing abstain.
    values = sorted(by_value.keys())
    first_att = min(
        (a for v in values for a in by_value[v]),
        key=lambda a: a.timestamp,
    )
    second_att = max(
        (a for v in values for a in by_value[v]),
        key=lambda a: a.timestamp,
    )
    if first_att.value == second_att.value:
        raise AttestationError(
            f"conflict detector fired but timestamps collapse to one value "
            f"for task={task_id} epoch={epoch}; cannot construct evidence pair"
        )
    obs = ConflictObservation(
        first=first_att,
        second=second_att,
        accused_candidates=(first_att.signer, second_att.signer),
    )
    # The critical line: return ABSTAIN_AGAINST, never ABSENT.
    return VoteKind.ABSTAIN_AGAINST, obs


def quorum_reached(votes: dict[str, int], q: int) -> bool:
    return votes.get("for", 0) >= q


def tally(vote: VoteKind, value: str, tallies: dict[str, dict[str, int]]) -> None:
    """
    ABSTAIN_AGAINST(value) counts as a negative vote: it decrements the
    conflicting value's tally and increments the opposite. ABSENT does neither.
    """
    if vote is VoteKind.FOR:
        tallies.setdefault(value, {"for": 0, "against": 0})["for"] += 1
    elif vote is VoteKind.ABSTAIN_AGAINST:
        tallies.setdefault(value, {"for": 0, "against": 0})["against"] += 1
    elif vote is VoteKind.ABSENT:
        # Silent withholding: the deadlock bug. Must never be returned on conflict.
        raise AttestationError(
            f"ABSENT returned on detected conflict for value={value}; "
            f"this is the f+1 symmetric-witness deadlock trigger"
        )
