# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-attest-a-quorum-result-when-byzantine-agents-can-equivocate-across-attestation-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-attest-a-quorum-result-when-byzantine-agents-can-equivocate-across-attestation-epochs.warrant.json
# Markdown SHA-256:   d8d5725487f0f215fe9e028ab9f560306dfb45cb7438af2e97e184d1e1baad71
# Code AST SHA-256:   1ccbf9abf356ed4f8f7d7c9b9f1add76d8c96ad76b1f3be8cc3cce36c1642fbd
# Verified Classes:   EquivocationDetected, MissingEpochOverlap, Attestation, AttestingInstance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EquivocationDetected(RuntimeError):
    """Raised when an instance is asked to attest a result that conflicts with a prior signed attestation for the same task."""


class MissingEpochOverlap(RuntimeError):
    """Raised when the current epoch's membership cannot be shown to overlap a prior certificate's signer set by >= f+1 agents."""


@dataclass
class Attestation:
    task_id: str
    result_hash: str
    epoch: int
    signers: frozenset


@dataclass
class AttestingInstance:
    agent_id: str
    f: int
    signed_tasks: dict = field(default_factory=dict)  # task_id -> Attestation

    def _result_hash(self, task_id: str, result: bytes, epoch: int) -> str:
        return hashlib.sha256(task_id.encode() + b"||" + result + b"||" + str(epoch).encode()).hexdigest()

    def attest(
        self,
        task_id: str,
        result: bytes,
        epoch: int,
        current_membership: frozenset,
        prior_certificate: Attestation | None,
        proof_of_absence_signers: frozenset | None,
    ) -> Attestation:
        new_hash = self._result_hash(task_id, result, epoch)

        # Condition 1: log continuity — refuse on conflicting prior signature.
        prior = self.signed_tasks.get(task_id)
        if prior is not None and prior.result_hash != new_hash:
            raise EquivocationDetected(
                f"agent {self.agent_id}: task {task_id} already attested as "
                f"{prior.result_hash[:12]} in epoch {prior.epoch}, "
                f"now asked to attest {new_hash[:12]} in epoch {epoch}"
            )

        # Condition 2: epoch overlap — must intersect prior signers by >= f+1,
        # or hold a proof-of-absence from >= f+1 agents.
        if prior_certificate is not None:
            overlap = current_membership & prior_certificate.signers
            if len(overlap) < self.f + 1:
                if not proof_of_absence_signers or len(proof_of_absence_signers) < self.f + 1:
                    raise MissingEpochOverlap(
                        f"agent {self.agent_id}: epoch {epoch} membership overlaps "
                        f"prior certificate signers in only {len(overlap)} agents "
                        f"(need {self.f + 1}); no proof-of-absence supplied"
                    )

        att = Attestation(task_id=task_id, result_hash=new_hash, epoch=epoch, signers=frozenset({self.agent_id}))
        self.signed_tasks[task_id] = att
        return att
