# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-capability-version-skew-during-a2a-v1-0-agent-card-discovery-before-committing-a-delegated-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-capability-version-skew-during-a2a-v1-0-agent-card-discovery-before-committing-a-delegated-task.warrant.json
# Markdown SHA-256:   e85f32af1bf8462cc811ac1cd237a409b198a1e668ab6c0291b8b5fd4897820e
# Code AST SHA-256:   dd8416b49cbab24874c5c6989bdaa5af2c13cd626d072e0b1bf776238c00b009
# Verified Classes:   SchemaHashMismatchError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class SchemaHashMismatchError(RuntimeError):
    """Raised when a remote skill's outputSchema hash has no registered parser.

    This is the boundary guard for silent A2A skill-schema drift: the
    protocolVersion matched, but the skill's schema semantics changed
    underneath a cached parser. Delegation must abort here, not at
    result-parse time.
    """


def canonical_hash(schema: dict[str, Any]) -> str:
    # Stable across key order and whitespace; the hash the parser registry
    # is keyed against.
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def resolve_delegation(
    remote_card: dict[str, Any],
    skill_id: str,
    parser_registry: dict[str, Any],
    expected_protocol: str = "1.0",
) -> Any:
    """Resolve a skill for delegation or refuse loudly.

    Enforces the invariant: protocol match alone is insufficient;
    the skill outputSchema hash must be registered.
    """
    if remote_card.get("protocolVersion") != expected_protocol:
        # Loud, safe failure.
        raise SchemaHashMismatchError(
            f"protocol mismatch: {remote_card.get('protocolVersion')!r} "
            f"!= {expected_protocol!r}"
        )

    skill = next(
        (s for s in remote_card.get("skills", []) if s.get("id") == skill_id),
        None,
    )
    if skill is None:
        raise SchemaHashMismatchError(f"skill {skill_id!r} not advertised")

    output_schema = skill.get("outputSchema")
    if output_schema is None:
        raise SchemaHashMismatchError(
            f"skill {skill_id!r} advertises no outputSchema; cannot bind parser"
        )

    h = canonical_hash(output_schema)
    parser = parser_registry.get(h)
    if parser is None:
        # The dangerous middle: protocol matched, schema drifted,
        # no parser for this revision. Refuse BEFORE task construction.
        raise SchemaHashMismatchError(
            f"skill {skill_id!r} outputSchema hash {h[:12]}… has no "
            f"registered parser; refusing delegation to avoid silent "
            f"result misparse (protocolVersion matched, schema drifted)"
        )
    return parser
