# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-discovered-a2a-agent-card-whose-capabilities-block-verifies-under-the-signature-but-whose-extensions-array-was-truncate.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-discovered-a2a-agent-card-whose-capabilities-block-verifies-under-the-signature-but-whose-extensions-array-was-truncate.warrant.json
# Markdown SHA-256:   8403f3e4c97513756843a8661148d822dca9fb41d96bc266e815bac0d3618ac0
# Code AST SHA-256:   05c321c79d4a320fec0b9826e7be1215944e5cf196c79e9f126d0ccdd52335b9
# Verified Classes:   AgentCardProjectionError, ExtensionNotDeclaredError, VerifiedCard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any

class AgentCardProjectionError(RuntimeError):
    """Raised when a card is verified or evaluated after a lossy projection."""

class ExtensionNotDeclaredError(RuntimeError):
    """Raised when a task requires an extension the remote card did not declare."""

@dataclass(frozen=True)
class VerifiedCard:
    raw_bytes: bytes
    parsed: dict[str, Any]
    digest: str

def fetch_and_verify(raw_bytes: bytes, jws_verify, declared_profile: str | None) -> VerifiedCard:
    # Invariant: verify the bytes we received, never a re-serialization.
    if declared_profile not in (None, "detached-payload", "jcs"):
        raise AgentCardProjectionError(f"unknown signature profile {declared_profile!r}")
    if not jws_verify(raw_bytes):
        raise AgentCardProjectionError("JWS failed over raw discovery bytes")
    parsed = json.loads(raw_bytes)  # parse AFTER verify, from same bytes
    digest = hashlib.sha256(raw_bytes).hexdigest()
    return VerifiedCard(raw_bytes=raw_bytes, parsed=parsed, digest=digest)

def assert_no_projection(card: VerifiedCard, claimed_digest: str) -> None:
    if claimed_digest != card.digest:
        raise AgentCardProjectionError(
            "capability decision referenced a projection, not the verified bytes"
        )

def check_delegation_eligibility(
    card: VerifiedCard,
    caller_supported_extensions: set[str],
    required_capabilities: set[str],
    required_extensions: set[str],
) -> None:
    caps = card.parsed.get("capabilities", {})
    declared_exts = set(card.parsed.get("extensions", []))

    missing_caps = required_capabilities - {k for k, v in caps.items() if v is True}
    if missing_caps:
        raise AgentCardProjectionError(f"capabilities not declared: {missing_caps}")

    # Extensions are part of the capability surface, not metadata.
    undeclared = required_extensions - declared_exts
    if undeclared:
        raise ExtensionNotDeclaredError(
            f"remote did not declare required extensions: {undeclared}"
        )
    unimplemented = required_extensions - caller_supported_extensions
    if unimplemented:
        raise ExtensionNotDeclaredError(
            f"caller runtime cannot honor extensions: {unimplemented}"
        )
