# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-collapse-when-a-delegated-aaif-credential-s-attenuation-proof-is-re-signed-by-an-intermediary-with-a-nar.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-collapse-when-a-delegated-aaif-credential-s-attenuation-proof-is-re-signed-by-an-intermediary-with-a-nar.warrant.json
# Markdown SHA-256:   3461eda454f6d3c7a184b586b4895f47066263bb601699041e8958e6fea5df3f
# Code AST SHA-256:   7fb81a8edcef516701fa873431085220535adcbf87f107a705aee0c17288b692
# Verified Classes:   AttenuationClockMismatch, ScopeFloorViolation, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttenuationClockMismatch(RuntimeError):
    """Raised when a child credential's effective validity, as evaluated by the
    verifier's clock, is not a subset of its parent's effective validity."""
    pass


class ScopeFloorViolation(RuntimeError):
    """Raised when a verifier falls back to a parent credential and would
    authorize a scope that the rejected child explicitly excluded."""
    pass


@dataclass(frozen=True)
class Credential:
    cred_id: str
    parent_id: Optional[str]
    not_before: float
    expires_at: float
    max_clock_skew: float
    scopes: frozenset

    def effective_interval(self, now: float) -> tuple:
        return (self.not_before - self.max_clock_skew,
                self.expires_at + self.max_clock_skew)


def verify_chain(child: Credential, parent: Credential, now: float) -> None:
    """Verify that child's effective window nests inside parent's, as seen by
    the single verifier clock `now`. Raises on non-nesting."""
    c_lo, c_hi = child.effective_interval(now)
    p_lo, p_hi = parent.effective_interval(now)
    if not (p_lo <= c_lo and c_hi <= p_hi):
        raise AttenuationClockMismatch(
            f"child {child.cred_id} effective window [{c_lo},{c_hi}] "
            f"not nested in parent {parent.cred_id} [{p_lo},{p_hi}] "
            f"at verifier clock {now}; skew_child={child.max_clock_skew} "
            f"skew_parent={parent.max_clock_skew}"
        )
    if not child.scopes.issubset(parent.scopes):
        raise AttenuationClockMismatch(
            f"child {child.cred_id} scopes not subset of parent {parent.cred_id}"
        )


def authorize_with_fallback(
    child: Credential,
    parent: Credential,
    requested_scope: str,
    now: float,
) -> str:
    """Authorize a request. If child is clock-rejected, fall back to parent
    but intersect the child's scope constraint as a floor."""
    c_lo, c_hi = child.effective_interval(now)
    child_live = c_lo <= now <= c_hi

    if child_live:
        if requested_scope not in child.scopes:
            raise ScopeFloorViolation(
                f"scope {requested_scope!r} not in live child {child.cred_id}"
            )
        return child.cred_id

    # Fallback path: child is clock-dead, but parent may still be live.
    p_lo, p_hi = parent.effective_interval(now)
    if not (p_lo <= now <= p_hi):
        raise AttenuationClockMismatch(
            f"both child {child.cred_id} and parent {parent.cred_id} "
            f"expired at verifier clock {now}"
        )

    # CRITICAL: parent-fallback must respect the child's scope as a floor,
    # even though the child is not live. Otherwise we silently escalate.
    if requested_scope not in child.scopes:
        raise ScopeFloorViolation(
            f"parent-fallback would authorize {requested_scope!r} which "
            f"child {child.cred_id} excluded; refusing escalation"
        )
    if requested_scope not in parent.scopes:
        raise ScopeFloorViolation(
            f"scope {requested_scope!r} not in parent {parent.cred_id}"
        )
    return parent.cred_id
