# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-reputation-attestation-equivocation-during-cross-org-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-reputation-attestation-equivocation-during-cross-org-capability-negotiation.warrant.json
# Markdown SHA-256:   bbd8d28625edbb8e52704eb8ebc017c788f8080531f692d0ce00077308bb15fa
# Code AST SHA-256:   7074d05bba4d634ca5a96069e793b3ac53f79d41db360986d34eaa43c2c3a99d
# Verified Classes:   AttestationEquivocationError, DigestReproductionError, CapabilityDescriptor, Attestation, AdmissionDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class AttestationEquivocationError(RuntimeError):
    """Raised when auditors attest to divergent property-sets under one digest."""


class DigestReproductionError(RuntimeError):
    """Raised when an auditor's signed digest cannot be reproduced from negotiated properties."""


@dataclass(frozen=True)
class CapabilityDescriptor:
    cap: str
    residency: str
    retention_hours: int
    rate_per_sec: int

    def canonical(self) -> bytes:
        # Consumer-controlled canonicalization: ALL policy fields included.
        return json.dumps(
            {
                "cap": self.cap,
                "residency": self.residency,
                "retention_hours": self.retention_hours,
                "rate_per_sec": self.rate_per_sec,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode()


@dataclass(frozen=True)
class Attestation:
    auditor_id: str
    signed_digest: str
    attested_properties: CapabilityDescriptor
    score: float
    session_nonce: str


@dataclass
class AdmissionDecision:
    outcome: str  # "ADMITTED" | "QUARANTINED" | "REJECTED"
    reason: str
    quarantined_auditors: list = field(default_factory=list)


def _digest(desc: CapabilityDescriptor) -> str:
    return hashlib.sha256(desc.canonical()).hexdigest()


def evaluate_attestations(
    negotiated: CapabilityDescriptor,
    session_nonce: str,
    attestations: list,
    reputation_threshold: float = 0.80,
) -> AdmissionDecision:
    if not attestations:
        raise AttestationEquivocationError("no attestations supplied for negotiation")

    consumer_digest = _digest(negotiated)
    qualifying = [a for a in attestations if a.score >= reputation_threshold]

    if not qualifying:
        return AdmissionDecision("REJECTED", "no auditor above reputation threshold")

    # Invariant 1: every qualifying attestation must be bound to THIS session.
    for a in qualifying:
        if a.session_nonce != session_nonce:
            raise AttestationEquivocationError(
                f"auditor {a.auditor_id} attested to a different session nonce"
            )

    # Invariant 2: every qualifying attestation's digest must be reproducible
    # from the negotiated property-set under the consumer's canonicalizer.
    for a in qualifying:
        if a.signed_digest != consumer_digest:
            raise DigestReproductionError(
                f"auditor {a.auditor_id} signed {a.signed_digest}, "
                f"consumer reproduces {consumer_digest} from negotiated properties"
            )

    # Invariant 3: digest match is NOT property match. Compare property-sets.
    property_sets = {a.attested_properties for a in qualifying}
    if len(property_sets) > 1:
        # Equivocation signature: same digest, different properties across auditors.
        return AdmissionDecision(
            "QUARANTINED",
            "cross-auditor property divergence under a shared digest",
            quarantined_auditors=[a.auditor_id for a in qualifying],
        )

    attested = next(iter(property_sets))
    if attested != negotiated:
        # Single property-set, but it disagrees with what we negotiated.
        return AdmissionDecision(
            "QUARANTINED",
            "attested properties differ from negotiated properties",
            quarantined_auditors=[a.auditor_id for a in qualifying],
        )

    return AdmissionDecision("ADMITTED", "digest and property-set both match negotiation")
