# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-aaif-verifiable-credential-was-issued-under-a-stale-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-aaif-verifiable-credential-was-issued-under-a-stale-delegation-chain.warrant.json
# Markdown SHA-256:   21c4532bca37565f4ef85ea9e5501a9a98fa61128c6d641aecb8afa29e88a44a
# Code AST SHA-256:   47a6960a990304eac306998910310e86e27f183e2e05853daa10b010791daaf3
# Verified Classes:   ChainLifetimeExceededError, DelegationLink
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class ChainLifetimeExceededError(RuntimeError):
    """Raised when a requested VC lifetime exceeds the delegation chain's remaining validity."""

    def __init__(self, requested_exp: datetime, ceiling: datetime, binding_link: str):
        self.requested_exp = requested_exp
        self.ceiling = ceiling
        self.binding_link = binding_link
        super().__init__(
            f"requested_exp={requested_exp.isoformat()} exceeds chain ceiling "
            f"{ceiling.isoformat()} set by link {binding_link!r}"
        )


@dataclass
class DelegationLink:
    issuer_did: str
    not_after: datetime
    scope: frozenset[str]


def issue_credential(
    chain: list[DelegationLink],
    requested_ttl: timedelta,
    now: datetime,
    leaf_scope: frozenset[str],
) -> datetime:
    if not chain:
        raise ChainLifetimeExceededError(now + requested_ttl, now, "<empty-chain>")

    for link in chain:
        if link.not_after <= now:
            raise ChainLifetimeExceededError(
                now + requested_ttl, link.not_after, link.issuer_did
            )

    binding = min(chain, key=lambda l: l.not_after)
    ceiling = binding.not_after
    requested_exp = now + requested_ttl

    if requested_exp > ceiling:
        raise ChainLifetimeExceededError(requested_exp, ceiling, binding.issuer_did)

    if not leaf_scope.issubset(chain[-1].scope):
        raise ChainLifetimeExceededError(requested_exp, ceiling, chain[-1].issuer_did)

    return requested_exp
