# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-quorum-view-of-shared-state-before-its-own-evidence-log-is-durable-the-pre-commit-durability-asymmetry-in-b.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-quorum-view-of-shared-state-before-its-own-evidence-log-is-durable-the-pre-commit-durability-asymmetry-in-b.warrant.json
# Markdown SHA-256:   3abf019cae7a3b599d88f5339d9f17ab982647f6b73af5c1d936f5c84d042941
# Code AST SHA-256:   642b847a18291969cfd388e05998343ba2bdebe41b7998929a1cefd5ba35ccbf
# Verified Classes:   PreCommitEvidenceDurabilityError, JustificationGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac


class PreCommitEvidenceDurabilityError(RuntimeError):
    """Raised when an agent attempts to vote before its evidence segment is durable and attested."""
    pass


class JustificationGapError(RuntimeError):
    """Raised at audit time when a committed quorum member cannot produce a verifiable segment."""
    pass


def durable_segment_root(segment_bytes: bytes, fsync_hook) -> str:
    # fsync_hook must return True only after the bytes are durably persisted.
    if not fsync_hook(segment_bytes):
        raise PreCommitEvidenceDurabilityError(
            "evidence segment not durable; refusing to compute a votable root"
        )
    return hashlib.sha256(segment_bytes).hexdigest()


def attest_and_vote(agent_id: str, task_id: str, epoch: int,
                    segment_bytes: bytes, fsync_hook, signing_key: bytes,
                    consensus_client) -> dict:
    root = durable_segment_root(segment_bytes, fsync_hook)
    payload = f"{task_id}:{root}:{epoch}".encode()
    sig = hmac.new(signing_key, payload, hashlib.sha256).hexdigest()
    vote = {"agent_id": agent_id, "task_id": task_id,
            "segment_root": root, "epoch": epoch, "signature": sig}
    # Vote only after durability + attestation; never before.
    consensus_client.broadcast_vote(vote)
    return vote


def audit_committed_task(committed_map: dict, presented_segments: dict,
                         verify_key_for) -> None:
    # committed_map: agent_id -> (segment_root, signature, epoch)
    # presented_segments: agent_id -> segment_bytes
    for agent_id, (expected_root, sig, epoch) in committed_map.items():
        seg = presented_segments.get(agent_id)
        if seg is None:
            raise JustificationGapError(
                f"agent {agent_id} committed a vote but presents no segment"
            )
        actual_root = hashlib.sha256(seg).hexdigest()
        if actual_root != expected_root:
            raise JustificationGapError(
                f"agent {agent_id} segment root mismatch: "
                f"expected {expected_root}, got {actual_root}"
            )
        key = verify_key_for(agent_id, epoch)
        payload = f"{committed_map[agent_id][2]}:{actual_root}:{epoch}".encode()
        expected_sig = hmac.new(key, payload, hashlib.sha256).hexdigest()
        if not hmac.compare_digest(expected_sig, sig):
            raise JustificationGapError(
                f"agent {agent_id} signature invalid at epoch {epoch}"
            )
