# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-verify-a-peer-s-signed-agent-card-before-honoring-a-reputation-weighted-route.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-verify-a-peer-s-signed-agent-card-before-honoring-a-reputation-weighted-route.warrant.json
# Markdown SHA-256:   f50656d4a7ae52fd9e2f6c61ba008b57ca315a7a210d2a2d1e5def9f5a9ca30b
# Code AST SHA-256:   602281232acfeda415327ae799f5996224fda04b10e6032d9c20293d65ff71aa
# Verified Classes:   ReputationCardMismatch, SignedAgentCard, AccrualEntry, ReputationLedger, ContinuityAttestation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ReputationCardMismatch(RuntimeError):
    """Raised when a reputation-weighted route would apply a score to a card
    hash that produced none of that score's accrual entries, with no attested
    continuity bridge."""
    pass


@dataclass(frozen=True)
class SignedAgentCard:
    logical_id: str
    endpoint: str
    capabilities: tuple[str, ...]
    signing_key_id: str

    def reputation_relevant_hash(self) -> str:
        # Signing key excluded: key rotation alone must not invalidate reputation.
        material = f"{self.logical_id}|{self.endpoint}|{','.join(sorted(self.capabilities))}"
        return hashlib.sha256(material.encode()).hexdigest()


@dataclass
class AccrualEntry:
    card_hash: str
    score: float
    tasks: int


@dataclass
class ReputationLedger:
    # logical_id -> accrual entries, each tagged with the card hash it was earned under
    entries: dict[str, list[AccrualEntry]] = field(default_factory=dict)

    def accrual_hashes(self, logical_id: str) -> set[str]:
        return {e.card_hash for e in self.entries.get(logical_id, [])}

    def weighted_score(self, logical_id: str) -> float:
        es = self.entries.get(logical_id, [])
        total = sum(e.tasks for e in es)
        if total == 0:
            return 0.0
        return sum(e.score * e.tasks for e in es) / total


@dataclass
class ContinuityAttestation:
    logical_id: str
    from_hash: str
    to_hash: str
    signed_by_trust_root: bool


def route_weight(
    card: SignedAgentCard,
    ledger: ReputationLedger,
    attestation: Optional[ContinuityAttestation],
    continuity_discount: float = 0.5,
) -> float:
    """Decide the reputation weight to apply to a discovered card.

    Raises ReputationCardMismatch when the card's reputation-relevant hash has
    no accrual history and no attested bridge from a hash that does.
    """
    presented = card.reputation_relevant_hash()
    accrual = ledger.accrual_hashes(card.logical_id)
    base = ledger.weighted_score(card.logical_id)

    if presented in accrual:
        return base  # accept-and-carry

    if (
        attestation is not None
        and attestation.signed_by_trust_root
        and attestation.logical_id == card.logical_id
        and attestation.to_hash == presented
        and attestation.from_hash in accrual
    ):
        return base * continuity_discount  # accept-and-quarantine

    raise ReputationCardMismatch(
        f"card hash {presented[:12]} for {card.logical_id!r} has no accrual "
        f"entries (known: {sorted(h[:12] for h in accrual)}) and no attested "
        f"continuity bridge; refusing to apply score {base:.3f}"
    )
