# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-capability-token-whose-delegation-chain-exceeds-the-issuer-s-trust-horizon-even-when-every-indiv.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-capability-token-whose-delegation-chain-exceeds-the-issuer-s-trust-horizon-even-when-every-indiv.warrant.json
# Markdown SHA-256:   0f9eea5fa713955e4322007b546dfb854ebf58b5c29eb7764b598ce6f64162ad
# Code AST SHA-256:   5a26fdba45074dc61ffedadff62274bf9cc5209bffed9158f1384c56e9763fcc
# Verified Classes:   TrustHorizonViolation, Link, RootHorizon, Chain
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TrustHorizonViolation(RuntimeError):
    """Raised when a delegated token's chain exceeds the root issuer's horizon."""
    pass


@dataclass
class Link:
    issuer_org: str
    issued_at: float          # epoch seconds
    expires_at: float
    scope: frozenset
    claimed_depth: int
    signature_valid: bool     # result of per-link crypto check


@dataclass
class RootHorizon:
    max_depth: int
    max_cumulative_live_ttl: float
    allowed_intermediates: frozenset
    present: bool = True


@dataclass
class Chain:
    root_horizon: RootHorizon
    links: list = field(default_factory=list)  # index 0 is the root token


def verify_delegated_chain(chain: Chain, now: float | None = None) -> None:
    now = time.time() if now is None else now

    if not chain.root_horizon.present:
        # Fail closed: federation policy requires bounded delegation.
        raise TrustHorizonViolation(
            "root token carries no horizon metadata; refusing unbounded delegation"
        )

    # (a) every link's signature must verify
    for i, link in enumerate(chain.links):
        if not link.signature_valid:
            raise TrustHorizonViolation(f"signature invalid at link {i}")

    # (b) monotonic attenuation + (c) recomputed chain metrics
    recomputed_depth = 0
    cumulative_live_ttl = 0.0
    prev_scope = None
    prev_expires = None

    for i, link in enumerate(chain.links):
        if i > 0:
            recomputed_depth += 1
            if link.claimed_depth != recomputed_depth:
                raise TrustHorizonViolation(
                    f"link {i} claims depth {link.claimed_depth} "
                    f"but recomputed depth is {recomputed_depth}"
                )
            if prev_scope is not None and not link.scope <= prev_scope:
                raise TrustHorizonViolation(f"scope escalation at link {i}")
            if prev_expires is not None and link.expires_at > prev_expires:
                raise TrustHorizonViolation(f"TTL extension at link {i}")
            if link.issuer_org not in chain.root_horizon.allowed_intermediates:
                raise TrustHorizonViolation(
                    f"intermediate org {link.issuer_org!r} not in allowed set"
                )
        # cumulative live time this link was actually alive
        cumulative_live_ttl += max(0.0, min(link.expires_at, now) - link.issued_at)
        prev_scope = link.scope
        prev_expires = link.expires_at

    if recomputed_depth > chain.root_horizon.max_depth:
        raise TrustHorizonViolation(
            f"chain depth {recomputed_depth} exceeds max_depth "
            f"{chain.root_horizon.max_depth}"
        )
    if cumulative_live_ttl > chain.root_horizon.max_cumulative_live_ttl:
        raise TrustHorizonViolation(
            f"cumulative live TTL {cumulative_live_ttl:.0f}s exceeds "
            f"max {chain.root_horizon.max_cumulative_live_ttl:.0f}s"
        )
