# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-agent-card-has-silently-degraded-across-heterogeneous-a2a-v1-0-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-agent-card-has-silently-degraded-across-heterogeneous-a2a-v1-0-registries.warrant.json
# Markdown SHA-256:   758ea025f95cc2762eb195dd4af1f997894d4c72accd7ce580e0530751d48a2e
# Code AST SHA-256:   a25e959a3d9afe91f9c189d3c815da00fc09b4cec2c9523823e24cab6d37be0b
# Verified Classes:   CardFidelityError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
import hashlib
from typing import Any

class CardFidelityError(RuntimeError):
    """Raised when a delivered Agent Card's signature is structurally inconclusive."""


REQUIRED_SIGNED_FIELDS = ("canonicalization", "algorithm", "value")


def _canonicalize_jcs(payload: dict[str, Any]) -> bytes:
    # Deterministic JSON canonicalization (RFC 8785 subset sufficient for this check).
    return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


CANONICALIZERS = {"JCS": _canonicalize_jcs}


def verify_card_fidelity(card: dict[str, Any]) -> bool:
    """
    Returns True only if the card is fidelity-attested: the signature block
    declares its canonicalization INSIDE the signed region, and recomputation
    from the received bytes reproduces the signature.
    """
    sig = card.get("signature")
    if not isinstance(sig, dict):
        raise CardFidelityError("card carries no signature block; cannot attest fidelity")

    for field in REQUIRED_SIGNED_FIELDS:
        if field not in sig:
            # This is the exact structural signature of a lossy re-emit:
            # algorithm present, canonicalization dropped by an intermediate schema.
            raise CardFidelityError(
                f"signature block missing required field '{field}'; "
                "card was likely reconstructed by a registry that did not preserve signing context"
            )

    canon_name = sig["canonicalization"]
    if canon_name not in CANONICALIZERS:
        raise CardFidelityError(f"unsupported canonicalization '{canon_name}'")

    # The signed region excludes only the signature value itself.
    signed_region = {k: v for k, v in card.items() if k != "signature"}
    signed_region["signature"] = {k: v for k, v in sig.items() if k != "value"}

    recomputed = hashlib.sha256(CANONICALIZERS[canon_name](signed_region)).hexdigest()
    if recomputed != sig["value"]:
        raise CardFidelityError(
            "signature does not reproduce from received bytes; "
            "payload was mutated after signing or canonicalization was applied post-mutation"
        )
    return True


def negotiate_or_refetch(card: dict[str, Any], origin_well_known: str) -> dict[str, Any]:
    try:
        verify_card_fidelity(card)
        return card
    except CardFidelityError as exc:
        # Do NOT negotiate against a degraded card. Defer to origin fetch.
        raise CardFidelityError(
            f"registry-delivered card is not fidelity-attested ({exc}); "
            f"refetch directly from {origin_well_known} before capability negotiation"
        )
