# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-task-despite-a-valid-agent-card-signature-unsigned-capability-claims-inside-the-skills-array-as-a-cross-vendo.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-task-despite-a-valid-agent-card-signature-unsigned-capability-claims-inside-the-skills-array-as-a-cross-vendo.warrant.json
# Markdown SHA-256:   56a2fcf104b0850084943d209ebe822a4f50e138ea5b94a9fc104d79b3c934e0
# Code AST SHA-256:   b9890f8b2523db832bf336c5f68b90d4ec549219cbb82f62d43658c2b229c614
# Verified Classes:   SkillProvenanceError, SignedCard, ResolvedSkill
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class SkillProvenanceError(RuntimeError):
    """Raised when a signed Agent Card's skill cannot be bound to an authenticated executor."""


@dataclass
class SignedCard:
    body: dict
    kid: str
    signature_valid: bool
    url: str


@dataclass
class ResolvedSkill:
    skill_id: str
    executor_url: str
    executor_kid: str
    side_effect: bool


def verify_executor_binding(card: SignedCard, nonce: str, endpoint_jws: Optional[str]) -> bool:
    """The endpoint must present a JWS over `nonce` signed by the same kid as the card."""
    if not endpoint_jws:
        return False
    # In production: parse JWS, verify against card.kid's public key, compare payload == nonce.
    return endpoint_jws.startswith("jws:") and nonce in endpoint_jws


def resolve_skill(card: SignedCard, skill_id: str, nonce: str, endpoint_jws: Optional[str]) -> ResolvedSkill:
    if not card.signature_valid:
        raise SkillProvenanceError(f"card signature invalid for kid={card.kid}")

    skills = [s for s in card.body.get("skills", []) if s.get("id") == skill_id]
    if not skills:
        raise SkillProvenanceError(f"skill {skill_id} not declared in card {card.kid}")

    skill = skills[0]
    side_effect = skill.get("sideEffect", True)  # default to side-effecting if unspecified

    # Guardrail: side-effecting skills require executor binding to the signing kid.
    if side_effect and not verify_executor_binding(card, nonce, endpoint_jws):
        delegation = card.body.get("extensions", {}).get("a2a.delegation")
        if not delegation:
            raise SkillProvenanceError(
                f"skill {skill_id} on {card.url} is side-effecting but executor is not bound to kid={card.kid} "
                f"and no signed delegation extension enumerates the downstream executor"
            )
        # Recurse into delegation chain (omitted): each hop must independently verify.
        raise SkillProvenanceError(
            f"skill {skill_id} delegated but downstream executor card not independently verified"
        )

    # Namespace-collision guard: (kid, skill_id) is the key, not skill_id alone.
    schema_hash = hashlib.sha256(json.dumps(skill.get("inputModes", [])).encode()).hexdigest()[:16]
    return ResolvedSkill(
        skill_id=f"{card.kid}:{skill_id}:{schema_hash}",
        executor_url=card.url,
        executor_kid=card.kid,
        side_effect=side_effect,
    )
