# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-audit-witness-has-silently-forked-its-own-ledger-before-signing-a-cross-org-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-audit-witness-has-silently-forked-its-own-ledger-before-signing-a-cross-org-attestation.warrant.json
# Markdown SHA-256:   22aa91beb0fd60fb43da87c03462842f53a769d3e638f355c90d68c1853008c6
# Code AST SHA-256:   aad76b4d2e6b4e937085546d241734e7ae2fb170694bffac4f585edd6d6472c1
# Verified Classes:   SplitViewWitnessError, SignedHead
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass
from typing import Dict, Tuple


class SplitViewWitnessError(RuntimeError):
    """Raised when a witness's signed head for an epoch disagrees across peers,
    or when no peer echo / consistency proof backs the uniqueness claim."""
    pass


@dataclass(frozen=True)
class SignedHead:
    witness_id: str
    epoch: int
    root: bytes
    sig: bytes


def _verify_witness_sig(head: SignedHead, witness_pubkey: bytes) -> bool:
    # In production this is Ed25519/ECDSA over (witness_id||epoch||root).
    mac = hmac.new(witness_pubkey, head.root + str(head.epoch).encode(), hashlib.sha256).digest()
    return hmac.compare_digest(mac, head.sig)


def consume_attestation(
    head: SignedHead,
    witness_pubkey: bytes,
    peer_echoes: Dict[str, SignedHead],   # peer_id -> head that peer received for this epoch
    prior_head: SignedHead | None,       # last head this instance accepted
    require_quorum: bool,
) -> None:
    """Gate an agent action on a witness attestation.

    Integrity is checked locally; uniqueness is checked against peer echoes.
    Raises SplitViewWitnessError if the witness forked its view.
    """
    if not _verify_witness_sig(head, witness_pubkey):
        raise SplitViewWitnessError(
            f"witness {head.witness_id} signature invalid at epoch {head.epoch}"
        )

    # Consistency: the new head must extend the prior head we already trust.
    if prior_head is not None:
        if head.epoch < prior_head.epoch:
            raise SplitViewWitnessError(
                f"epoch regression: {head.epoch} < {prior_head.epoch}"
            )
        # A proper implementation requests and verifies a Merkle consistency proof
        # here; we assert the proof was supplied and verified upstream.
        # If it was not, we cannot claim uniqueness even with a valid signature.

    # Uniqueness: compare against what the witness told other peers this epoch.
    matching = 0
    for peer_id, echo in peer_echoes.items():
        if echo.epoch != head.epoch:
            continue
        if echo.witness_id != head.witness_id:
            continue
        if echo.root != head.root:
            raise SplitViewWitnessError(
                f"split view: witness {head.witness_id} told peer {peer_id} "
                f"root {echo.root.hex()[:16]} but told us {head.root.hex()[:16]} "
                f"at epoch {head.epoch}"
            )
        matching += 1

    if require_quorum and matching < 1:
        raise SplitViewWitnessError(
            f"no peer echo for epoch {head.epoch}; single-witness signature "
            f"proves integrity but not uniqueness"
        )


def guarded_tool_invocation(
    head: SignedHead,
    witness_pubkey: bytes,
    peer_echoes: Dict[str, SignedHead],
    prior_head: SignedHead | None,
    destructive: bool,
) -> None:
    # Destructive actions demand peer-witnessed uniqueness; benign ones do not.
    consume_attestation(
        head=head,
        witness_pubkey=witness_pubkey,
        peer_echoes=peer_echoes,
        prior_head=prior_head,
        require_quorum=destructive,
    )
