# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-its-scoped-delegation-token-when-a-sub-agent-presents-a-chain-of-attenuated-credentials.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-its-scoped-delegation-token-when-a-sub-agent-presents-a-chain-of-attenuated-credentials.warrant.json
# Markdown SHA-256:   ee124594d4930c17182008eeb92f036e88935d7b5ebdbfc0fafbe63f98f40284
# Code AST SHA-256:   65df3469e737a26359805ee5849e17f73f4923030348a41dc61d0faaea301ae2
# Verified Classes:   ChainAuthorityError, ScopedToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class ChainAuthorityError(RuntimeError):
    """Raised when a delegation chain's effective authority is violated."""
    pass


@dataclass(frozen=True)
class ScopedToken:
    issuer: str
    subject: str
    scope: frozenset
    not_after: float          # absolute epoch seconds
    parent_id: Optional[str]  # None for root


def verify_chain(
    chain: list,               # ordered root -> leaf
    now: float,
    revoked_ids: frozenset,
    scope_required: frozenset,
) -> float:
    """
    Re-walk a delegation chain and return its effective authority deadline.
    Enforces the intersection invariant: no hop may extend the window,
    and no ancestor revocation may be masked by a cached leaf verdict.
    """
    if not chain:
        raise ChainAuthorityError("empty delegation chain")

    # 1. Ancestor revocation propagation: any revoked hop kills the chain.
    for idx, tok in enumerate(chain):
        token_id = f"{tok.issuer}->{tok.subject}:{tok.not_after}"
        if token_id in revoked_ids:
            raise ChainAuthorityError(
                f"hop {idx} ({token_id}) is revoked; chain authority void"
            )

    # 2. Temporal intersection: effective deadline is the minimum hop deadline.
    effective_not_after = min(tok.not_after for tok in chain)

    # 3. Widening detection: a hop whose not_after exceeds its parent's
    #    is structurally suspect even if the signature validates.
    for idx in range(1, len(chain)):
        if chain[idx].not_after > chain[idx - 1].not_after + 1e-9:
            raise ChainAuthorityError(
                f"hop {idx} widens time window "
                f"({chain[idx].not_after} > parent {chain[idx - 1].not_after}); "
                f"attenuator exceeded its own authority"
            )

    # 4. Scope intersection: required scope must be granted at every hop.
    for idx, tok in enumerate(chain):
        if not scope_required.issubset(tok.scope):
            raise ChainAuthorityError(
                f"hop {idx} does not grant required scope "
                f"{sorted(scope_required)}; has {sorted(tok.scope)}"
            )

    # 5. Deadline check against the intersected window, not the leaf's.
    if now >= effective_not_after:
        raise ChainAuthorityError(
            f"chain effective deadline {effective_not_after} passed (now={now}); "
            f"leaf claimed {chain[-1].not_after}"
        )

    return effective_not_after


def cache_ttl(chain: list, now: float) -> float:
    """
    A leaf verdict may only be cached for the shortest ancestor's remaining
    lifetime. Keying a cache on the leaf hash alone is unsound.
    """
    effective = min(tok.not_after for tok in chain)
    ttl = effective - now
    if ttl <= 0:
        raise ChainAuthorityError(
            "refusing to cache an already-expired chain verdict"
        )
    return ttl
