# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-as-authoritative-versus-advisory-during-cross-org-task-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-a2a-v1-0-agent-card-as-authoritative-versus-advisory-during-cross-org-task-delegation.warrant.json
# Markdown SHA-256:   dc59003445a1612b96d7096b3193126a5f8e828790e71ffe02dc8829f02b705e
# Code AST SHA-256:   71b8ea4066b6e1478b827bf65e1778771cab74a35dba315b8dba7bc63beef3fc
# Verified Classes:   AgentCardRoutingTrustError, AttestedEndpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from urllib.parse import urlparse


class AgentCardRoutingTrustError(RuntimeError):
    """Raised when a signed AgentCard's routing target cannot be bound to the
    principal that signed the card, at the moment of task delegation."""


@dataclass(frozen=True)
class AttestedEndpoint:
    origin: str
    principal_fingerprint: str  # e.g. SHA-256 of the receiving cert's SPKI
    ttl_seconds: int


def _origin(url: str) -> str:
    p = urlparse(url)
    return f"{p.scheme}://{p.netloc}"


def resolve_delegation_target(
    card_url: str,
    card_body: dict,
    card_signing_principal: str,
    attested: dict[str, AttestedEndpoint],
    now_epoch: int,
    attestation_ttl: int = 300,
) -> str:
    """Decide whether card_body['url'] is authoritative for routing.

    Returns the endpoint URL to submit the task to, or raises if the routing
    field cannot be bound to the card-signing principal.
    """
    declared_url = card_body.get("url")
    if not declared_url:
        raise AgentCardRoutingTrustError(
            f"card at {card_url} declares no url; cannot route delegation"
        )

    card_origin = _origin(card_url)
    declared_origin = _origin(declared_url)

    # Same-origin: the serving principal is the receiving principal.
    if declared_origin == card_origin:
        return declared_url

    # Cross-origin: require an independent attestation of the receiving
    # principal, and require it to match the card-signing principal.
    entry = attested.get(declared_origin)
    if entry is None:
        raise AgentCardRoutingTrustError(
            f"cross-origin routing target {declared_origin} has no attestation; "
            f"card signature alone does not authorize this endpoint"
        )

    if now_epoch - entry.ttl_seconds > attestation_ttl:
        raise AgentCardRoutingTrustError(
            f"attestation for {declared_origin} expired "
            f"({now_epoch - entry.ttl_seconds}s old, ttl={attestation_ttl}s); "
            f"re-probe before delegating"
        )

    if entry.principal_fingerprint != card_signing_principal:
        raise AgentCardRoutingTrustError(
            f"principal mismatch: card signed by {card_signing_principal}, "
            f"endpoint {declared_origin} presents {entry.principal_fingerprint}"
        )

    return declared_url


def submit_task(card_url: str, card_body: dict, signing_principal: str,
                attested: dict[str, AttestedEndpoint], now_epoch: int,
                payload: dict) -> dict:
    target = resolve_delegation_target(
        card_url, card_body, signing_principal, attested, now_epoch
    )
    # ... perform message/send against `target` ...
    return {"target": target, "status": "submitted"}
