# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-skill-whose-declared-schema-is-a-strict-superset-of-the-requested-one-the-capability-shadowing-failure-in-a2a.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-skill-whose-declared-schema-is-a-strict-superset-of-the-requested-one-the-capability-shadowing-failure-in-a2a.warrant.json
# Markdown SHA-256:   cfc574084c8e88cd293ab3d16b3fbb6edc8f75f09112b8953bf28ff4fdab3706
# Code AST SHA-256:   38ebb7ea0db05f02b39f00eed55790ea513a2c248c3b33745e54483e3d58f582
# Verified Classes:   CapabilityShadowingError, SkillDecl
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any


class CapabilityShadowingError(RuntimeError):
    """Raised when a delegated skill silently substitutes a superset contract."""


@dataclass(frozen=True)
class SkillDecl:
    skill_id: str
    required: frozenset[str]
    optional: frozenset[str]
    open_properties: bool


def resolve_and_bind(
    requested: SkillDecl,
    candidates: list[SkillDecl],
    payload: dict[str, Any],
    *,
    equivalence_warrant: bool = False,
) -> SkillDecl:
    payload_keys = frozenset(payload)
    declared = requested.required | requested.optional

    # Shadow signal: caller set a field the requested skill never declared.
    shadow_fields = payload_keys - declared
    if shadow_fields and not equivalence_warrant:
        raise CapabilityShadowingError(
            f"payload carries undeclared fields {sorted(shadow_fields)}; "
            f"requested skill {requested.skill_id!r} cannot honor them"
        )

    for cand in candidates:
        if cand.skill_id == requested.skill_id:
            if shadow_fields and not cand.open_properties:
                raise CapabilityShadowingError(
                    f"requested skill {cand.skill_id!r} declares closed properties "
                    f"but payload has {sorted(shadow_fields)}"
                )
            return cand

    # No exact-id match: any prefix/overlap match is a shadowing candidate.
    for cand in candidates:
        if cand.skill_id.startswith(requested.skill_id):
            if not equivalence_warrant:
                raise CapabilityShadowingError(
                    f"refusing prefix substitution {requested.skill_id!r} -> "
                    f"{cand.skill_id!r} without signed equivalence warrant"
                )
            if not (cand.required <= payload_keys):
                raise CapabilityShadowingError(
                    f"superset skill {cand.skill_id!r} missing required "
                    f"{sorted(cand.required - payload_keys)}"
                )
            return cand

    raise CapabilityShadowingError(
        f"no skill equivalent to {requested.skill_id!r} on remote card"
    )
