# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-validate-the-a2a-v1-0-agent-card-signature-chain-before-accepting-a-delegated-task-envelope-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-validate-the-a2a-v1-0-agent-card-signature-chain-before-accepting-a-delegated-task-envelope-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   d35579ae68b1bdae6084c3dda727cb678de5d6c4de5a85ce699fe927fe43a186
# Code AST SHA-256:   567a4e45eddcf76493479e4afb8415bedd032a78be9ab1656d25aba01b0116e9
# Verified Classes:   DelegationAdmissionError, Card, Hop
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping


class DelegationAdmissionError(RuntimeError):
    """Raised when a task envelope is signature-valid but authority-invalid."""


@dataclass(frozen=True)
class Card:
    agent_id: str
    key_id: str
    capabilities: frozenset[str]
    root_trusted: bool
    valid_until: int


@dataclass(frozen=True)
class Hop:
    from_agent: str
    to_agent: str
    capability: str
    key_id: str
    prior_task_hash: str | None


def admit_envelope(
    chain: list[Hop],
    cards: Mapping[str, Card],
    now: int,
    trusted_roots: frozenset[str],
) -> str:
    """Return an execution token only if the full chain predicate passes.

    Predicate per hop N:
      1. card exists for hop.from_agent and is root-trusted
      2. card.key_id == hop.key_id  (no silent rotation fallback)
      3. card.valid_until > now     (freshness)
      4. for N > 1: hop.capability in card.capabilities (attenuation)
      5. chain is append-only and references prior hop hash
    """
    if not chain:
        raise DelegationAdmissionError("empty delegation chain")

    prior_hash: str | None = None
    for idx, hop in enumerate(chain):
        card = cards.get(hop.from_agent)
        if card is None:
            raise DelegationAdmissionError(
                f"hop {idx}: no card resolved for {hop.from_agent}"
            )
        if not card.root_trusted or card.agent_id not in trusted_roots:
            raise DelegationAdmissionError(
                f"hop {idx}: card for {hop.from_agent} not chained to trusted root"
            )
        if card.key_id != hop.key_id:
            # fail-closed on rotation; do NOT re-fetch-and-retry
            raise DelegationAdmissionError(
                f"hop {idx}: keyId mismatch card={card.key_id} envelope={hop.key_id}"
            )
        if card.valid_until <= now:
            raise DelegationAdmissionError(
                f"hop {idx}: card for {hop.from_agent} expired at {card.valid_until}"
            )
        if idx > 0:
            if hop.capability not in card.capabilities:
                raise DelegationAdmissionError(
                    f"hop {idx}: attenuation violated — {hop.from_agent} "
                    f"forwarded '{hop.capability}' not in its card"
                )
            if hop.prior_task_hash != prior_hash:
                raise DelegationAdmissionError(
                    f"hop {idx}: chain discontinuity, prior hash mismatch"
                )
        prior_hash = hashlib.sha256(
            f"{hop.from_agent}|{hop.to_agent}|{hop.capability}|{hop.key_id}".encode()
        ).hexdigest()

    return "exec:" + prior_hash  # execution token, only emitted on full pass
