# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-byzantine-peer-s-verified-claim-when-the-quorum-is-heterogeneous-and-the-verifier-is-weaker-than-the-producer.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-byzantine-peer-s-verified-claim-when-the-quorum-is-heterogeneous-and-the-verifier-is-weaker-than-the-producer.warrant.json
# Markdown SHA-256:   f2c97057da9665a230b1d7e0835a32f3b3699a426ca5c529cb764ca4fd5cb3a1
# Code AST SHA-256:   26d8c1a0eabcf23846126f0641c9bf11765dcd300b236425e0ab52b0ae289489
# Verified Classes:   UnverifiableQuorumError, Voter, Claim, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UnverifiableQuorumError(RuntimeError):
    """Raised when a quorum is reached by count but not by competence."""
    pass


@dataclass
class Voter:
    agent_id: str
    capacity_tokens: int          # max artifact size this voter can actually inspect
    tier: int                     # higher = stronger model


@dataclass
class Claim:
    producer_id: str
    producer_tier: int
    artifact: str
    claimed_verifications: int    # e.g. "tests_passed"
    diff_hash: str
    complexity_tokens: int        # tokens needed to fully inspect the artifact


@dataclass
class Vote:
    voter_id: str
    decision: str                 # "APPROVE" | "REJECT" | "ABSTAIN"
    witness: Optional[str] = None # re-execution log / line citation / recomputed hash
    inspected_tokens: int = 0


def compute_witness_hash(artifact: str, verifications: int) -> str:
    return hashlib.sha256(f"{artifact}|{verifications}".encode()).hexdigest()


def tally_quorum(
    claim: Claim,
    voters: list[Voter],
    votes: list[Vote],
    f: int,
) -> str:
    """Count quorum, but only count votes that carry a checkable witness
    produced by a voter whose capacity covers the claim's complexity."""
    voter_map = {v.agent_id: v for v in voters}
    effective_approvals = 0
    abstentions = 0

    for vote in votes:
        voter = voter_map.get(vote.voter_id)
        if voter is None:
            raise UnverifiableQuorumError(
                f"vote from unknown voter {vote.voter_id}"
            )

        if vote.decision == "ABSTAIN":
            abstentions += 1
            continue

        if vote.decision != "APPROVE":
            continue

        # Competence gate: the voter must have been able to inspect the artifact.
        if voter.capacity_tokens < claim.complexity_tokens:
            # Honest but uninformed — does not count as independent evidence.
            abstentions += 1
            continue

        # Witness gate: approval must cite a verifiable artifact-derived fact.
        if vote.witness is None:
            abstentions += 1
            continue

        expected = compute_witness_hash(claim.artifact, claim.claimed_verifications)
        if vote.witness != expected:
            # Witness does not match the artifact — treat as reject, not approve.
            continue

        effective_approvals += 1

    n = len(voters)
    threshold = (n + f + 1) // 2

    if effective_approvals >= threshold:
        return "ACCEPTED"

    # Distinguish "rejected on evidence" from "could not verify".
    if effective_approvals + abstentions >= threshold and effective_approvals < threshold:
        raise UnverifiableQuorumError(
            f"quorum unreachable by competence: {effective_approvals} effective "
            f"approvals, {abstentions} abstentions, threshold {threshold} "
            f"(claim complexity {claim.complexity_tokens} tokens exceeds "
            f"weakest approving voter capacity). Escalate to re-execution or "
            f"decompose the artifact."
        )

    return "REJECTED"
