# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-that-outlives-its-own-attestation-key-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-that-outlives-its-own-attestation-key-epoch.warrant.json
# Markdown SHA-256:   b677407f103a11648441a58113f38358f18ca2792cdc55f8ca77187ec3ddec95
# Code AST SHA-256:   c1afcc9e7eb5c11c530a9e43791c71ba480efc3be35d79ed9c0eb47514d40a74
# Verified Classes:   EpochSkewError, Commitment, EpochKeyRegistry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Set


class EpochSkewError(RuntimeError):
    """Raised when a commitment's key epoch is no longer reconstructable at attestation time."""
    pass


@dataclass
class Commitment:
    task_hash: str
    epoch: int
    signers: Set[str]
    signatures: Dict[str, bytes] = field(default_factory=dict)


class EpochKeyRegistry:
    def __init__(self):
        # epoch -> {agent_id -> public_key}
        self._keys: Dict[int, Dict[str, bytes]] = {}
        # epoch -> set of live commitment task_hashes referencing it
        self._refs: Dict[int, Set[str]] = field(default_factory=dict)

    def install(self, epoch: int, keys: Dict[str, bytes]) -> None:
        self._keys[epoch] = keys
        self._refs.setdefault(epoch, set())

    def pin(self, commitment: Commitment) -> None:
        if commitment.epoch not in self._keys:
            raise EpochSkewError(
                f"cannot pin commitment {commitment.task_hash}: epoch {commitment.epoch} unknown"
            )
        self._refs[commitment.epoch].add(commitment.task_hash)

    def release(self, commitment: Commitment) -> None:
        self._refs.get(commitment.epoch, set()).discard(commitment.task_hash)

    def evict(self, epoch: int) -> None:
        # Guardrail: never evict an epoch that still backs a live commitment.
        if self._refs.get(epoch):
            raise EpochSkewError(
                f"refusing to evict epoch {epoch}: {len(self._refs[epoch])} live commitments reference it"
            )
        self._keys.pop(epoch, None)
        self._refs.pop(epoch, None)

    def verify_commitment(self, commitment: Commitment, threshold: int) -> bool:
        # Resolve keys by the commitment's *own* epoch, never the "active" epoch.
        epoch_keys = self._keys.get(commitment.epoch)
        if epoch_keys is None:
            raise EpochSkewError(
                f"epoch {commitment.epoch} for commitment {commitment.task_hash} "
                f"was evicted before attestation; cannot reconstruct quorum"
            )
        valid = sum(
            1 for agent, sig in commitment.signatures.items()
            if agent in epoch_keys and _sig_ok(epoch_keys[agent], commitment, sig)
        )
        return valid >= threshold


def _sig_ok(pub: bytes, c: Commitment, sig: bytes) -> bool:
    # Placeholder for real signature check; binds task, params, and epoch.
    return hashlib.sha256(pub + c.task_hash.encode() + str(c.epoch).encode()).digest() == sig


def attest_result(registry: EpochKeyRegistry, commitment: Commitment, threshold: int) -> bool:
    if not registry.verify_commitment(commitment, threshold):
        raise EpochSkewError(
            f"attestation rejected for {commitment.task_hash}: commitment quorum "
            f"not verifiable under epoch {commitment.epoch}"
        )
    return True
