# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-a-committed-task-when-a-byzantine-quorum-member-equivocates-across-two-commitment-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-a-committed-task-when-a-byzantine-quorum-member-equivocates-across-two-commitment-epochs.warrant.json
# Markdown SHA-256:   635209365e5aa6a050ba4adebba82a4e936dade5b3eb73275d49f377f6a9d9f3
# Code AST SHA-256:   883a3014dccadaad55a8cb7d1eaee9a9a3f7f7f7d7db667e016b5b2e05ff59a7
# Verified Classes:   EquivocationQuarantineError, Certificate
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet, Optional


class EquivocationQuarantineError(RuntimeError):
    """Raised when a task cannot be safely bound to a single commitment certificate."""


@dataclass(frozen=True)
class Certificate:
    task_id: str
    param_hash: str
    epoch: int
    signers: FrozenSet[str]

    def digest(self) -> str:
        body = f"{self.task_id}|{self.param_hash}|{self.epoch}|{','.join(sorted(self.signers))}"
        return hashlib.sha256(body.encode()).hexdigest()


def bind_single_certificate(
    task_id: str,
    candidates: list[Certificate],
    epoch_advice: dict[str, int],
    f: int,
    quorum: int,
) -> Certificate:
    """
    Bind exactly one certificate for task_id, or raise EquivocationQuarantineError.

    epoch_advice maps voter_id -> highest epoch that voter has attested to.
    Requires len(epoch_advice) >= f+1 to be a valid advice quorum.
    """
    if not candidates:
        raise EquivocationQuarantineError(f"no certificate for {task_id}")

    for c in candidates:
        if c.task_id != task_id:
            raise EquivocationQuarantineError(f"certificate task mismatch: {c.task_id}")
        if len(c.signers) < quorum:
            raise EquivocationQuarantineError(
                f"certificate epoch={c.epoch} has {len(c.signers)} signers < quorum {quorum}"
            )

    if len(epoch_advice) < f + 1:
        raise EquivocationQuarantineError(
            f"epoch-advice quorum too small ({len(epoch_advice)} < {f + 1}); cannot order certificates"
        )

    if len(candidates) == 1:
        only = candidates[0]
        witnessed_max = max(epoch_advice.values())
        if only.epoch < witnessed_max:
            raise EquivocationQuarantineError(
                f"sole certificate epoch={only.epoch} is below witnessed max {witnessed_max}"
            )
        return only

    # Multiple certificates: require a convicting intersection and epoch ordering.
    a, b = candidates[0], candidates[1]
    if a.param_hash == b.param_hash:
        # Same content, different epochs: bind highest witnessed epoch.
        witnessed_max = max(epoch_advice.values())
        best = max(candidates, key=lambda c: c.epoch)
        if best.epoch < witnessed_max:
            raise EquivocationQuarantineError(
                f"best epoch {best.epoch} below witnessed max {witnessed_max}"
            )
        return best

    intersection = a.signers & b.signers
    if len(intersection) < f + 1:
        raise EquivocationQuarantineError(
            f"signer intersection {len(intersection)} < f+1={f + 1}; cannot convict equivocator"
        )

    higher, lower = (a, b) if a.epoch > b.epoch else (b, a)
    # Honest voters in the intersection must have attested to the higher epoch.
    honest_witnesses = [v for v in intersection if epoch_advice.get(v, -1) >= higher.epoch]
    if len(honest_witnesses) < 1:
        raise EquivocationQuarantineError(
            f"no intersection voter attests to epoch {higher.epoch}; ordering unprovable"
        )

    # Convicting evidence exists: quarantine lower, bind higher.
    return higher
