# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-peer-s-a2a-agent-card-has-silently-drifted-from-the-mcp-tool-schema-it-advertises-under-the-same-capability-name.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-peer-s-a2a-agent-card-has-silently-drifted-from-the-mcp-tool-schema-it-advertises-under-the-same-capability-name.warrant.json
# Markdown SHA-256:   b3c6d16b45617dc08b6869997573a9b27638bdc20c3fd29c6a439aa9e8909a28
# Code AST SHA-256:   b54a65abc3d5ab9c51c9415a8f65c83e93ea9ce22b3dd02d9b386c7f693df4d1
# Verified Classes:   DescriptorDriftError, AgentCardSkill, McpToolSchema
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DescriptorDriftError(RuntimeError):
    """Raised when an A2A agent card and the co-published MCP tool schema
    disagree on the contract for the same capability, beyond the declared
    version-lineage compatibility window."""

    def __init__(self, capability: str, detail: str):
        self.capability = capability
        self.detail = detail
        super().__init__(f"descriptor drift on '{capability}': {detail}")


@dataclass
class AgentCardSkill:
    skill_id: str
    declared_version: str
    described_params: set[str]
    schema_digest: Optional[str] = None  # vendor extension; None => unverifiable


@dataclass
class McpToolSchema:
    name: str
    version: str
    required_params: set[str]
    schema_digest: str
    compatible_predecessors: set[str] = field(default_factory=set)


def check_conformance(
    skill: AgentCardSkill,
    tool: McpToolSchema,
    *,
    require_digest: bool = True,
) -> str:
    """Returns 'consistent' | 'unverifiable'. Raises DescriptorDriftError on
    provable divergence. Must be called at cache-fill, before dispatch."""
    if skill.skill_id != tool.name:
        raise DescriptorDriftError(
            skill.skill_id, f"skill bound to tool '{tool.name}'"
        )

    # Version lineage check: card may lag the tool by a declared predecessor.
    if skill.declared_version != tool.version:
        if skill.declared_version not in tool.compatible_predecessors:
            raise DescriptorDriftError(
                skill.skill_id,
                f"card version {skill.declared_version!r} not in "
                f"compatible predecessors of tool version {tool.version!r}",
            )

    # Parameter-set check: the card must not describe params the schema
    # rejects, and must not omit params the schema requires.
    phantom = skill.described_params - (tool.required_params | set())
    missing = tool.required_params - skill.described_params
    if phantom or missing:
        raise DescriptorDriftError(
            skill.skill_id,
            f"phantom_params={sorted(phantom)} missing_params={sorted(missing)}",
        )

    # Digest check: only meaningful when the card carries a comparable artifact.
    if skill.schema_digest is None:
        if require_digest:
            raise DescriptorDriftError(
                skill.skill_id,
                "card carries no schema_digest; contract unverifiable",
            )
        return "unverifiable"

    if skill.schema_digest != tool.schema_digest:
        raise DescriptorDriftError(
            skill.skill_id,
            f"schema_digest mismatch: card={skill.schema_digest} "
            f"tool={tool.schema_digest}",
        )

    return "consistent"


def discover_and_gate(skill: AgentCardSkill, tool: McpToolSchema) -> str:
    try:
        verdict = check_conformance(skill, tool)
    except DescriptorDriftError:
        # Do NOT demote peer health here — the peer is healthy, metadata stale.
        raise
    if verdict == "unverifiable":
        return "dispatch_tagged_unverified_contract"
    return "dispatch"
