# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-equivocation-is-masked-by-heterogeneous-quorum-thresholds-in-a-byzantine-agent-collective.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-equivocation-is-masked-by-heterogeneous-quorum-thresholds-in-a-byzantine-agent-collective.warrant.json
# Markdown SHA-256:   3153e1f0d639591d6529da417827a63e61ff0e2d55ee16df4150160e46cfb7e3
# Code AST SHA-256:   3da6cede9bf2da038aa442e5afc0cdf0195dd21db116080863df8e10de466c85
# Verified Classes:   EquivocationMaskedByWeightForwarding
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class EquivocationMaskedByWeightForwarding(RuntimeError):
    """Raised when a weighted quorum certificate is issued without
    verifying that the weighted intersection of conflicting certificates
    exceeds the maximum colluding weight."""
    pass


def verify_weighted_quorum(certificates, max_colluding_weight, threshold):
    """
    certificates: list of dicts, each with:
        'proposal_hash': str
        'votes': list of (agent_id, weight, message_nonce, signature)
    Returns the winning proposal_hash if exactly one certificate is valid
    and no conflicting certificate shares weight with it.
    """
    # 1) Every vote must be bound to (proposal_hash, message_nonce) by signature.
    for cert in certificates:
        for agent_id, weight, nonce, sig in cert["votes"]:
            if not sig or nonce is None:
                raise EquivocationMaskedByWeightForwarding(
                    f"unbound vote from {agent_id} on {cert['proposal_hash']}: "
                    "weight is not cryptographically committed to message"
                )

    # 2) Deduplicate weight per (agent_id, message_nonce) within a certificate.
    seen = {}
    for cert in certificates:
        key = cert["proposal_hash"]
        seen.setdefault(key, {})
        for agent_id, weight, nonce, _ in cert["votes"]:
            if (agent_id, nonce) in seen[key]:
                raise EquivocationMaskedByWeightForwarding(
                    f"weight double-counted for {agent_id} nonce={nonce} "
                    f"on {key}"
                )
            seen[key][(agent_id, nonce)] = weight

    # 3) Compute weighted totals and check threshold.
    totals = {h: sum(w.values()) for h, w in seen.items()}
    qualified = [h for h, t in totals.items() if t >= threshold]
    if len(qualified) == 0:
        raise EquivocationMaskedByWeightForwarding("no certificate met threshold")
    if len(qualified) > 1:
        # 4) Conflicting quorums: check weighted intersection.
        h1, h2 = qualified[0], qualified[1]
        shared_agents = set(a for (a, _) in seen[h1]) & set(a for (a, _) in seen[h2])
        shared_weight = sum(seen[h1][k] for k in seen[h1] if k[0] in shared_agents)
        if shared_weight <= max_colluding_weight:
            raise EquivocationMaskedByWeightForwarding(
                f"conflicting quorums {h1} and {h2} share weight "
                f"{shared_weight} <= max_colluding_weight {max_colluding_weight}; "
                "equivocation is structurally undetectable"
            )
        raise EquivocationMaskedByWeightForwarding(
            f"conflicting quorums {h1} and {h2} both qualified"
        )

    return qualified[0]
