# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-agent-card-whose-declared-capabilities-were-negotiated-against-a-different-runtime-profile.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-agent-card-whose-declared-capabilities-were-negotiated-against-a-different-runtime-profile.warrant.json
# Markdown SHA-256:   18cad0be1518b8886d69dfc08b013902da9b7c03a4fbf4c464bfe0d774e3926e
# Code AST SHA-256:   9e861f28d7781ca9151c244ad7856aed910cc4a0414422e3fdf373d7e0e8c6f1
# Verified Classes:   CardTrustViolation, AgentCard, ProbeRegistry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CardTrustViolation(RuntimeError):
    """Raised when a consumer attempts to branch control flow on an unconfirmed card field."""
    pass


@dataclass
class AgentCard:
    peer_id: str
    version: Optional[str]
    capabilities: dict
    skills: list
    raw_hash: str = field(default="")

    def __post_init__(self):
        if not self.raw_hash:
            self.raw_hash = hashlib.sha256(
                repr((self.version, self.capabilities, self.skills)).encode()
            ).hexdigest()


@dataclass
class ProbeRegistry:
    confirmed: dict = field(default_factory=dict)   # (peer_id, cap) -> bool
    budgets: dict = field(default_factory=dict)     # peer_id -> effective input budget
    card_hashes: dict = field(default_factory=dict) # peer_id -> raw_hash at probe time

    def is_confirmed(self, card: AgentCard, cap: str) -> bool:
        key = (card.peer_id, cap)
        # A probe result is only valid for the exact card bytes it was run against.
        if self.card_hashes.get(card.peer_id) != card.raw_hash:
            return False
        return self.confirmed.get(key, False)

    def confirm(self, card: AgentCard, cap: str, result: bool) -> None:
        self.card_hashes[card.peer_id] = card.raw_hash
        self.confirmed[(card.peer_id, cap)] = result


def commit_control_flow(card: AgentCard, cap: str, probes: ProbeRegistry) -> bool:
    """
    Called before the consumer branches control flow on a capability field.
    Refuses if the field is unconfirmed or the card has changed since probing.
    """
    if cap not in card.capabilities:
        raise CardTrustViolation(
            f"peer {card.peer_id}: capability {cap!r} not present in card"
        )
    if not probes.is_confirmed(card, cap):
        raise CardTrustViolation(
            f"peer {card.peer_id}: capability {cap!r} advertised={card.capabilities[cap]!r} "
            f"but unconfirmed for card hash {card.raw_hash[:12]}; "
            f"run probe before committing control flow"
        )
    return card.capabilities[cap]


def enforce_budget(card: AgentCard, payload_tokens: int, probes: ProbeRegistry) -> None:
    """
    Called before dispatch. Refuses if payload exceeds the producer's effective budget,
    or if no budget has been probed and the payload exceeds the consumer's own budget.
    """
    effective = probes.budgets.get(card.peer_id)
    if effective is None:
        raise CardTrustViolation(
            f"peer {card.peer_id}: no probed budget; cannot dispatch {payload_tokens} tokens "
            f"without sentinel probe (card declares no budget field)"
        )
    if payload_tokens > effective:
        raise CardTrustViolation(
            f"peer {card.peer_id}: payload {payload_tokens} exceeds probed budget {effective}"
        )
