# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-capability-attestation-expiry-against-in-flight-federated-message-routing-across-policy-aware-brokers.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-capability-attestation-expiry-against-in-flight-federated-message-routing-across-policy-aware-brokers.warrant.json
# Markdown SHA-256:   3825e76c49261a236a1abb593116f67fd5cd13dbfc6ce9fce0de223fc02d56e0
# Code AST SHA-256:   55ec97c20ab130584c53aa652d77bec765272b35470dbbac9aeadd04e7361eaf
# Verified Classes:   AttestationRouteExhausted, DelegationChainInvalid, Attestation, RouteCommitment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class AttestationRouteExhausted(RuntimeError):
    """Raised when a message's attestation cannot survive the remaining route."""


class DelegationChainInvalid(RuntimeError):
    """Raised when a hop attempts to refresh an attestation without a valid chain."""


@dataclass
class Attestation:
    sub: str
    caps: list[str]
    not_before: float
    not_after: float
    delegation_chain: list[str] = field(default_factory=list)


@dataclass
class RouteCommitment:
    hops: list[str]
    max_dwell: dict[str, float]  # hop -> max seconds
    hop_trace: list[tuple[str, float]] = field(default_factory=list)  # (hop, dequeue_ts)


def admit_at_terminal(
    att: Attestation,
    route: RouteCommitment,
    now: float,
    eval_budget: float,
    quota_ledger: dict[tuple[str, str], int],
    quota_requested: int,
    quota_limit: int,
) -> None:
    # 1. Verify delegation chain terminates at the original principal.
    if att.delegation_chain and att.delegation_chain[-1] != att.sub:
        raise DelegationChainInvalid(
            f"delegation chain {att.delegation_chain} does not terminate at sub={att.sub}"
        )

    # 2. Sum observed dwell and verify against per-hop budgets.
    observed_dwell = 0.0
    for hop, dequeue_ts in route.hop_trace:
        budget = route.max_dwell.get(hop)
        if budget is None:
            raise AttestationRouteExhausted(f"hop {hop} not in route commitment")
        observed_dwell += max(0.0, dequeue_ts - att.not_before) if not route.hop_trace else 0.0
    # Simpler: total elapsed from not_before to now must fit with eval budget.
    remaining = att.not_after - now
    if remaining < eval_budget:
        raise AttestationRouteExhausted(
            f"attestation expires in {remaining:.1f}s, eval budget {eval_budget:.1f}s"
        )

    # 3. Quota drawn against attestation identity, not message identity.
    key = (att.sub, ",".join(sorted(att.caps)))
    current = quota_ledger.get(key, 0)
    if current + quota_requested > quota_limit:
        raise AttestationRouteExhausted(
            f"quota overrun: {current}+{quota_requested} > {quota_limit} for {key}"
        )
    quota_ledger[key] = current + quota_requested


def refresh_at_hop(
    att: Attestation,
    hop_id: str,
    hop_authority: str,
    can_delegate: bool,
    now: float,
    new_ttl: float,
) -> Attestation:
    if not can_delegate or hop_id not in att.delegation_chain and hop_authority != att.sub:
        raise DelegationChainInvalid(
            f"hop {hop_id} ({hop_authority}) cannot refresh attestation for sub={att.sub}"
        )
    return Attestation(
        sub=att.sub,  # principal preserved
        caps=att.caps,
        not_before=now,
        not_after=now + new_ttl,
        delegation_chain=att.delegation_chain + [hop_id],
    )
