# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-signed-agent-card-despite-a-valid-signature-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-peer-s-signed-agent-card-despite-a-valid-signature-chain.warrant.json
# Markdown SHA-256:   472e22d2a1242b5c10cbdf51fae54f1abf2f9cb765af4ba8f51eb59647af607d
# Code AST SHA-256:   17fe8fd3d088ca19615a3ac16b29070706efef7c4b39fb29fb105fd84a4c2433
# Verified Classes:   CapabilityProvenanceError, SignerCert, AgentCard
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

IDENTITY_FIELDS = {"agent_name", "endpoint", "public_key"}
BEHAVIORAL_FIELDS = {"capabilities", "max_delegation_depth", "audience", "data_residency", "tool_scopes"}


class CapabilityProvenanceError(RuntimeError):
    """Raised when a signed Agent Card asserts a behavioral field its signer was not warranted to assert."""


@dataclass
class SignerCert:
    subject: str
    warrants: dict[str, Optional[object]]  # field_class -> warrant object (None = identity-only)


@dataclass
class AgentCard:
    fields: dict[str, object]
    chain: list[SignerCert]  # root first, leaf (card signer) last
    audience: list[str]
    nonce: str


def verify_card(card: AgentCard, verifier_id: str, expected_nonce: str) -> None:
    if card.nonce != expected_nonce:
        raise CapabilityProvenanceError(f"replay binding failed: nonce {card.nonce!r} != {expected_nonce!r}")

    wildcard = "*" in card.audience
    if wildcard and any(f in BEHAVIORAL_FIELDS for f in card.fields):
        raise CapabilityProvenanceError("wildcard audience cannot warrant behavioral fields")

    if verifier_id not in card.audience and not wildcard:
        raise CapabilityProvenanceError(f"audience does not bind verifier {verifier_id!r}")

    leaf = card.chain[-1]
    for name, value in card.fields.items():
        if name in IDENTITY_FIELDS:
            continue
        if name not in BEHAVIORAL_FIELDS:
            raise CapabilityProvenanceError(f"unknown field class {name!r} cannot be safely ignored")

        warrant = leaf.warrants.get(name)
        if warrant is None:
            raise CapabilityProvenanceError(
                f"signer {leaf.subject!r} holds no warrant for behavioral field {name!r}"
            )
        if hasattr(warrant, "covers") and not warrant.covers(value):
            raise CapabilityProvenanceError(
                f"value {value!r} for {name!r} exceeds signer {leaf.subject!r} warrant"
            )

    # scope narrowing: each hop's warrant set must be a subset of its parent's
    for parent, child in zip(card.chain, card.chain[1:]):
        extra = set(child.warrants) - set(parent.warrants)
        if extra:
            raise CapabilityProvenanceError(
                f"scope widening at hop {child.subject!r}: asserts {sorted(extra)} not warranted by {parent.subject!r}"
            )

    # effective delegation depth is the minimum warranted along the path
    depths = [c.warrants.get("max_delegation_depth") for c in card.chain if "max_delegation_depth" in c.warrants]
    if depths:
        effective = min(d for d in depths if d is not None)
        if card.fields.get("max_delegation_depth", 0) > effective:
            raise CapabilityProvenanceError(
                f"asserted delegation depth {card.fields['max_delegation_depth']} exceeds warranted {effective}"
            )
