# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-capability-attestation-whose-trust-chain-re-anchors-mid-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-capability-attestation-whose-trust-chain-re-anchors-mid-warrant.warrant.json
# Markdown SHA-256:   bb41232ae8ec84f265513ea35bed414bdda4f4452f09a0e7921b65e16a87bdf0
# Code AST SHA-256:   b39ace3007fe83feb7f3d7cbb9f21235e6f38b4631f917edf5ba4326db875d89
# Verified Classes:   RootDiscontinuity, TierPromotionExceeded, MalformedReanchor, Warrant, ReanchorAssertion
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RootDiscontinuity(RuntimeError):
    """Raised when a warrant chain re-anchors without a valid, counter-signed re-anchor assertion."""


class TierPromotionExceeded(RuntimeError):
    """Raised when a counter-signed re-anchor promotes beyond the resource's max promotable delta."""


class MalformedReanchor(RuntimeError):
    """Raised when a re-anchor assertion does not name both origin and terminal roots."""


@dataclass(frozen=True)
class Warrant:
    signer_root: str          # trust root whose key signed this hop
    origin_root: str          # root(W_0), carried forward across re-signing
    depth: int
    capability: str


@dataclass(frozen=True)
class ReanchorAssertion:
    from_root: str
    to_root: str
    tier_delta: int
    counter_signed_by_resource_owner: bool


def verify_federated_attestation(
    chain: list[Warrant],
    assertion: Optional[ReanchorAssertion],
    resource_root: str,
    resource_max_promotable_delta: int,
) -> str:
    """Return the tier at which the invocation is authorized, or raise."""
    if not chain:
        raise RootDiscontinuity("empty warrant chain")

    origin = chain[0].origin_root
    terminal = chain[-1].signer_root

    # Origin-root continuity must hold across every hop's carried-forward field.
    for hop in chain:
        if hop.origin_root != origin:
            raise RootDiscontinuity(
                f"origin root mutated mid-chain: {origin} -> {hop.origin_root}"
            )

    if origin == terminal:
        return terminal  # continuous, no re-anchor

    # Re-anchored chain: require a well-formed, counter-signed assertion.
    if assertion is None:
        raise RootDiscontinuity(
            f"chain re-anchored {origin} -> {terminal} with no assertion; "
            f"origin vetting tier unknown for resource rooted at {resource_root}"
        )
    if assertion.from_root != origin or assertion.to_root != terminal:
        raise MalformedReanchor(
            f"assertion names {assertion.from_root}->{assertion.to_root}, "
            f"chain is {origin}->{terminal}"
        )
    if not assertion.counter_signed_by_resource_owner:
        raise RootDiscontinuity(
            "re-anchor assertion lacks resource-owner counter-signature; "
            "unilateral broker promotion rejected"
        )
    if assertion.tier_delta > resource_max_promotable_delta:
        raise TierPromotionExceeded(
            f"tier delta {assertion.tier_delta} exceeds resource max "
            f"{resource_max_promotable_delta}"
        )
    # Authorized at the lower (origin) tier, not the promoted terminal tier.
    return origin
