# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-card-is-stale-ttl-less-discovery-caching-and-the-cross-org-delegation-handshake-divergence-in-a2a-v1-0.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-card-is-stale-ttl-less-discovery-caching-and-the-cross-org-delegation-handshake-divergence-in-a2a-v1-0.warrant.json
# Markdown SHA-256:   f017614ae1cb388fa5cd336f6a3736f087e1b0144d3c7391877d019b888ae6a7
# Code AST SHA-256:   22ca2070f2555f19064d8df21ae0cc129155514ec8df81898481e06a8a8e94e2
# Verified Classes:   CardFingerprintMismatch, CardDivergence, CardFingerprint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CardFingerprintMismatch(RuntimeError):
    """Raised when the served Agent Card no longer matches the cached fingerprint."""


class CardDivergence(CardFingerprintMismatch):
    """Raised when re-fetch shows a different organization/name — possible hijack."""


@dataclass(frozen=True)
class CardFingerprint:
    digest: str
    organization: str
    name: str


def compute_fingerprint(card: dict[str, Any]) -> CardFingerprint:
    """Fingerprint over semantically load-bearing fields only.

    Deliberately excludes 'description' and 'capabilities' (which churn
    harmlessly) and includes skill ids + input schemas + resolved security
    endpoints (which are the fields whose drift breaks delegation).
    """
    skills = sorted(
        (s["id"], json.dumps(s.get("inputSchema", {}), sort_keys=True))
        for s in card.get("skills", [])
    )
    schemes = sorted(
        (name, json.dumps(spec.get("flows", {}), sort_keys=True))
        for name, spec in card.get("securitySchemes", {}).items()
    )
    payload = json.dumps(
        {"skills": skills, "securitySchemes": schemes}, sort_keys=True
    ).encode()
    return CardFingerprint(
        digest=hashlib.sha256(payload).hexdigest(),
        organization=card.get("provider", {}).get("organization", ""),
        name=card.get("name", ""),
    )


def verify_delegation(
    cached: CardFingerprint,
    served_card: dict[str, Any],
    response_status: int,
    response_body: dict[str, Any] | None = None,
) -> None:
    """Validate a delegation attempt against the cached card fingerprint.

    Call this BEFORE any retry on 401/404/422. Transport-level retries on
    these codes are the failure mode this guard exists to prevent.
    """
    if response_status == 409 and (response_body or {}).get("error") == "CARD_FINGERPRINT_MISMATCH":
        fresh = compute_fingerprint(served_card)
        if fresh.organization != cached.organization or fresh.name != cached.name:
            raise CardDivergence(
                f"endpoint now serves {fresh.organization}/{fresh.name}; "
                f"cached was {cached.organization}/{cached.name}; abort and quarantine"
            )
        if fresh.digest != cached.digest:
            raise CardFingerprintMismatch(
                f"stale cache: skill/scheme drift detected; re-negotiate. "
                f"cached={cached.digest[:12]} served={fresh.digest[:12]}"
            )
        return

    if response_status in (401, 404, 422):
        fresh = compute_fingerprint(served_card)
        if fresh.digest != cached.digest:
            raise CardFingerprintMismatch(
                f"semantic drift on {response_status}; do not retry transport, "
                f"re-fetch and re-negotiate. cached={cached.digest[:12]} "
                f"served={fresh.digest[:12]}"
            )
        # Fingerprint matches but request still rejected → genuine transient
        # or a skill-level bug; safe to hand to the transport retry path.
        return
