# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-auditors-when-quorum-weight-is-computed-over-self-declared-capability-claims.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-auditors-when-quorum-weight-is-computed-over-self-declared-capability-claims.warrant.json
# Markdown SHA-256:   4368d946d4543ded27e5f099b05e2b29d77d48545059f0ea165f4d03f6e27da0
# Code AST SHA-256:   fa08a475b02e766975bb1410bd56f62c65aa3e8014dcce91616aa23ab7103e28
# Verified Classes:   UnverifiedWeightClaimError, CapabilityManifest, QuorumRound
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class UnverifiedWeightClaimError(RuntimeError):
    """Raised when a node's self-declared capability weight would contribute
    to quorum without behavioral evidence, violating weight-provenance."""
    pass


@dataclass
class CapabilityManifest:
    node_id: str
    claimed_tier: str
    weight: float
    behavioral_evidence: float = 0.0  # 0.0 = none, 1.0 = fully confirmed


@dataclass
class QuorumRound:
    manifests: Dict[str, CapabilityManifest] = field(default_factory=dict)
    votes: Dict[str, str] = field(default_factory=dict)

    def add_manifest(self, m: CapabilityManifest) -> None:
        self.manifests[m.node_id] = m

    def cast_vote(self, node_id: str, decision: str) -> None:
        if node_id not in self.manifests:
            raise UnverifiedWeightClaimError(
                f"vote from {node_id} with no capability manifest"
            )
        self.votes[node_id] = decision

    def effective_weight(self, node_id: str) -> float:
        m = self.manifests[node_id]
        total = sum(x.weight for x in self.manifests.values())
        cap = total / 3.0

        # Weight above the median tier requires behavioral evidence.
        median = sorted(x.weight for x in self.manifests.values())[
            len(self.manifests) // 2
        ]
        if m.weight > median and m.behavioral_evidence < 1.0:
            raise UnverifiedWeightClaimError(
                f"node {node_id} claims weight {m.weight:.2f} > median "
                f"{median:.2f} with evidence {m.behavioral_evidence:.2f}; "
                f"refusing to grant unverified weight"
            )

        # Hard cap: no single node may exceed 1/3 of total weight.
        return min(m.weight, cap)

    def tally(self, decision: str) -> float:
        return sum(
            self.effective_weight(nid)
            for nid, d in self.votes.items()
            if d == decision
        )

    def has_quorum(self, decision: str) -> bool:
        total = sum(self.effective_weight(nid) for nid in self.manifests)
        return self.tally(decision) >= (2.0 / 3.0) * total


def run_round(round_obj: QuorumRound) -> str:
    if round_obj.has_quorum("ACCEPT"):
        return "ACCEPT"
    if round_obj.has_quorum("REJECT"):
        return "REJECT"
    raise UnverifiedWeightClaimError(
        "no decision reached: quorum unreachable under verified weights"
    )
