# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-spiffe-svid-when-the-aaif-attestation-chain-is-structurally-valid-but-the-delegation-depth-excee.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-spiffe-svid-when-the-aaif-attestation-chain-is-structurally-valid-but-the-delegation-depth-excee.warrant.json
# Markdown SHA-256:   1677711f9732c8c82b70215ad6cdac74238acf3d9e64eeaf63e5d1697a292d21
# Code AST SHA-256:   7fbf05818ebfc2263901b1ed373bbfb2118080314e9069a757bb1452ae5e0b12
# Verified Classes:   StaleDelegatedEvidenceError, SVIDHop, RuntimeFingerprint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleDelegatedEvidenceError(RuntimeError):
    """Raised when a structurally valid delegated SVID carries attestation
    evidence older than its depth-adjusted freshness horizon, or when the
    leaf's runtime fingerprint diverges from the evidence it asserts."""


@dataclass
class SVIDHop:
    depth: int
    attested_at: float          # epoch seconds when evidence was captured
    image_digest: str           # evidence claim carried by this hop
    node_claim: str
    signature_valid: bool = True
    trust_bundle_current: bool = True


@dataclass
class RuntimeFingerprint:
    image_digest: str
    node_claim: str


def verify_delegated_chain(
    hops: list[SVIDHop],
    leaf_runtime: RuntimeFingerprint,
    re_attestation_horizon: float,
    delegation_ttl: float,
    depth_budget: int,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # Gate 1: structural validity (necessary, not sufficient).
    for hop in hops:
        if not hop.signature_valid or not hop.trust_bundle_current:
            raise StaleDelegatedEvidenceError(
                f"structural failure at depth {hop.depth}"
            )

    # Gate 2: depth-budget exhaustion.
    leaf = hops[-1]
    if leaf.depth > depth_budget:
        raise StaleDelegatedEvidenceError(
            f"delegation depth {leaf.depth} exceeds budget {depth_budget}; "
            f"re-attestation checkpoint required"
        )

    # Gate 3: depth-aware evidence freshness, evaluated per hop.
    for hop in hops:
        evidence_age = now - hop.attested_at
        allowed_age = min(re_attestation_horizon, delegation_ttl / (hop.depth + 1))
        if evidence_age > allowed_age:
            raise StaleDelegatedEvidenceError(
                f"stale-by-depth at hop {hop.depth}: evidence_age={evidence_age:.1f}s "
                f"> allowed_age={allowed_age:.1f}s "
                f"(horizon={re_attestation_horizon}s, ttl={delegation_ttl}s)"
            )

    # Gate 4: evidence/runtime divergence at the leaf.
    if leaf.image_digest != leaf_runtime.image_digest:
        raise StaleDelegatedEvidenceError(
            f"image digest divergence: SVID asserts {leaf.image_digest}, "
            f"runtime reports {leaf_runtime.image_digest}"
        )
    if leaf.node_claim != leaf_runtime.node_claim:
        raise StaleDelegatedEvidenceError(
            f"node claim divergence: SVID asserts {leaf.node_claim}, "
            f"runtime reports {leaf_runtime.node_claim}"
        )
