# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-a2a-gateway-is-laundering-trust-through-transitive-warrant-attenuation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-a2a-gateway-is-laundering-trust-through-transitive-warrant-attenuation.warrant.json
# Markdown SHA-256:   34a8b53d1a8e2f2fd72f94b81f4e8195976c38ba9812ec212f3af9d2405bff01
# Code AST SHA-256:   f45d9b3b6ee37b7ce10e9efadacce9a6d5e1018b5484414bbb88fce842dae9c4
# Verified Classes:   TrustLaunderingError, ProvenanceEdge, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TrustLaunderingError(RuntimeError):
    """Raised when a mediated warrant cannot prove its full provenance chain."""


@dataclass
class ProvenanceEdge:
    issuer_domain: str
    warrant_id: str
    attenuation_delta: str  # e.g. "read:dataset/42 -> read:dataset/42:metadata-only"


@dataclass
class Warrant:
    warrant_id: str
    issuer_domain: str
    scope: str
    audience: str
    ttl_seconds: int
    provenance: list[ProvenanceEdge] = field(default_factory=list)
    degraded: bool = False
    attenuation_reason: Optional[str] = None


def mediate_inbound(
    inbound: Warrant,
    local_domain: str,
    max_federation_depth: int,
    live_trusted_domains: set[str],
) -> Warrant:
    """
    Gateway-side mediation: validate an inbound warrant and mint a re-brokered
    child warrant. Enforces the provenance invariant before minting.
    """
    # Depth-1 direct-peer warrants may omit provenance only if the peer is a
    # direct trust root.
    if not inbound.provenance:
        if inbound.issuer_domain not in live_trusted_domains:
            raise TrustLaunderingError(
                f"warrant {inbound.warrant_id} from {inbound.issuer_domain} "
                f"has no provenance and issuer is not a direct trust root"
            )
    else:
        # Every hop in the chain must be currently trusted by this domain.
        for edge in inbound.provenance:
            if edge.issuer_domain not in live_trusted_domains:
                raise TrustLaunderingError(
                    f"provenance hop {edge.issuer_domain} "
                    f"(warrant {edge.warrant_id}) is no longer trusted by "
                    f"{local_domain}; refusing to re-broker"
                )

    # Bound the chain length. Beyond this the receiver cannot enumerate the
    # trust assumptions, so the warrant is rejected regardless of scope.
    if len(inbound.provenance) >= max_federation_depth:
        raise TrustLaunderingError(
            f"warrant {inbound.warrant_id} provenance depth "
            f"{len(inbound.provenance)} exceeds {local_domain} "
            f"max_federation_depth={max_federation_depth}"
        )

    # Any attenuation must be explicitly annotated; silent narrowing is a
    # reasoning-divergence vector and is treated as a hard failure here.
    if inbound.degraded and not inbound.attenuation_reason:
        raise TrustLaunderingError(
            f"warrant {inbound.warrant_id} is degraded but carries no "
            f"attenuation_reason; downstream planners cannot distinguish "
            f"reduced capability from empty result"
        )

    child = Warrant(
        warrant_id=f"{local_domain}:{inbound.warrant_id}:child",
        issuer_domain=local_domain,
        scope=inbound.scope,
        audience=inbound.audience,
        ttl_seconds=max(1, inbound.ttl_seconds - 60),
        provenance=inbound.provenance
        + [ProvenanceEdge(inbound.issuer_domain, inbound.warrant_id, "rebroker")],
        degraded=inbound.degraded,
        attenuation_reason=inbound.attenuation_reason,
    )
    return child
