# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-successful-mcp-a2a-capability-translation-as-evidence-of-authorization-rather-than-reachability-and-why-the.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-successful-mcp-a2a-capability-translation-as-evidence-of-authorization-rather-than-reachability-and-why-the.warrant.json
# Markdown SHA-256:   f084acf570889d00cf78852014dfefe24d34e1e9b8548adbe3f866dd05ef03f0
# Code AST SHA-256:   bf22efe0635bc73f2710bd0e24799495ba2a4f73de74c462987e18138515f7b5
# Verified Classes:   WarrantUnsatisfiableError, CardIdentityDriftError, Warrant, Skill, AgentCard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class WarrantUnsatisfiableError(RuntimeError):
    """Raised when an MCP tool is reachable but no valid A2A warrant exists."""
    pass


class CardIdentityDriftError(RuntimeError):
    """Raised when the remote Agent Card id changed under a cached warrant."""
    pass


@dataclass
class Warrant:
    aud: str                      # bound Agent Card id
    scope: frozenset[str]
    principal_chain: tuple[str, ...]
    expires_at: float

    def chain_hash(self) -> str:
        return hashlib.sha256("|".join(self.principal_chain).encode()).hexdigest()


@dataclass
class Skill:
    name: str
    required_scopes: frozenset[str]


@dataclass
class AgentCard:
    id: str
    skills: dict[str, Skill] = field(default_factory=dict)


def bridge_task(
    card: AgentCard,
    skill_name: str,
    warrant: Optional[Warrant],
    now: float,
    trusted_principals: frozenset[str],
) -> dict:
    skill = card.skills.get(skill_name)
    if skill is None:
        raise WarrantUnsatisfiableError(
            f"skill {skill_name!r} not advertised by card {card.id!r}"
        )

    if warrant is None:
        # Reachable but unauthorized: must NOT silently degrade.
        raise WarrantUnsatisfiableError(
            f"card {card.id!r} reachable, skill {skill_name!r} present, "
            f"but no warrant supplied"
        )

    if warrant.aud != card.id:
        # Cached warrant bound to a different card identity (e.g. staging).
        raise CardIdentityDriftError(
            f"warrant aud {warrant.aud!r} != card id {card.id!r}; "
            f"invalidate cache and re-request scopes"
        )

    if warrant.expires_at <= now:
        raise WarrantUnsatisfiableError(
            f"warrant for aud {warrant.aud!r} expired at {warrant.expires_at}"
        )

    if not skill.required_scopes.issubset(warrant.scope):
        missing = skill.required_scopes - warrant.scope
        raise WarrantUnsatisfiableError(
            f"warrant scope missing {sorted(missing)} for skill {skill_name!r}"
        )

    if not warrant.principal_chain or warrant.principal_chain[-1] not in trusted_principals:
        raise WarrantUnsatisfiableError(
            f"delegation chain terminates at untrusted principal "
            f"{warrant.principal_chain[-1] if warrant.principal_chain else None!r}"
        )

    return {
        "skill": skill_name,
        "warrant_aud": warrant.aud,
        "principal_chain_hash": warrant.chain_hash(),
    }
