# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-delegated-aaif-credential-chains-when-scope-attenuation-is-monotonic-but-capability-tokens-are-minted-against-a-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-delegated-aaif-credential-chains-when-scope-attenuation-is-monotonic-but-capability-tokens-are-minted-against-a-stale.warrant.json
# Markdown SHA-256:   7cb45caac07a74980b7ad01ff7dbaf0ad9ddd1fa0bae34748ef5c8f5d392e273
# Code AST SHA-256:   9f838a780e548511cd6d80bc860bd3fce6c4e80e139474cc0e395692a9df0b8d
# Verified Classes:   ContainmentStaleError, Scope, CapToken, ChainVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ContainmentStaleError(RuntimeError):
    """Raised when a delegated capability token's scope is not contained in the
    root principal's *live* effective scope, even though it was contained in the
    parent's minted snapshot. Snapshot-only verification is unsound here."""
    pass


@dataclass
class Scope:
    perms: frozenset  # e.g. {"read", "write"}

    def __le__(self, other: "Scope") -> bool:
        return self.perms <= other.perms


@dataclass
class CapToken:
    token_id: str
    subject: str
    scope: Scope
    parent_id: str
    minted_at: float
    ttl: float
    parent_snapshot_scope: Scope  # scope of parent AT MINT TIME

    def expired(self, now: float) -> bool:
        return now > self.minted_at + self.ttl


@dataclass
class ChainVerifier:
    # live scope registry: token_id -> current Scope (root + each ancestor)
    live_scope: dict = field(default_factory=dict)
    # revocation propagation latency bound, seconds
    propagation_bound: float = 30.0

    def verify(self, chain: list, now: float = None) -> None:
        """chain is ordered root-first .. leaf-last. Verifies composed live
        containment, not pairwise snapshot containment."""
        now = now if now is not None else time.time()
        if not chain:
            raise ContainmentStaleError("empty chain")

        # 1. expiry
        for tok in chain:
            if tok.expired(now):
                raise ContainmentStaleError(f"token {tok.token_id} expired")

        # 2. if remaining TTL exceeds propagation bound, snapshot evidence is
        #    insufficient; we MUST have live scope for every ancestor.
        leaf = chain[-1]
        remaining = (leaf.minted_at + leaf.ttl) - now
        need_live = remaining > self.propagation_bound

        # 3. composed live containment: leaf.scope <= root.live_scope
        root = chain[0]
        root_live = self.live_scope.get(root.token_id)
        if need_live and root_live is None:
            raise ContainmentStaleError(
                f"leaf {leaf.token_id} TTL remaining {remaining:.0f}s > "
                f"propagation bound {self.propagation_bound:.0f}s but live "
                f"scope for root {root.token_id} unavailable; "
                f"snapshot-only verification refused"
            )
        effective_root = root_live if root_live is not None else root.scope

        if not (leaf.scope <= effective_root):
            raise ContainmentStaleError(
                f"leaf scope {sorted(leaf.scope.perms)} not contained in live "
                f"root scope {sorted(effective_root.perms)} "
                f"(snapshot said {sorted(leaf.parent_snapshot_scope.perms)})"
            )

        # 4. transitive attenuation against live ancestors, not snapshots
        for i in range(1, len(chain)):
            child, parent = chain[i], chain[i - 1]
            parent_eff = self.live_scope.get(parent.token_id, parent.scope)
            if not (child.scope <= parent_eff):
                raise ContainmentStaleError(
                    f"hop {parent.token_id}->{child.token_id}: child scope "
                    f"{sorted(child.scope.perms)} exceeds live parent "
                    f"{sorted(parent_eff.perms)}"
                )
