# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-delegated-credential-from-a-scope-it-never-actually-held-transitive-scope-amplification-in-aaif-exchange-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-delegated-credential-from-a-scope-it-never-actually-held-transitive-scope-amplification-in-aaif-exchange-chains.warrant.json
# Markdown SHA-256:   9c5adb11f3d1381e5323e9080a3fa76b7a10da35ae3d0073e786a7567730783b
# Code AST SHA-256:   e322facac02977229727c81a8b7c2a49183d2aafa63cd1f4ab584654d9925b26
# Verified Classes:   ScopeAmplificationError, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from datetime import datetime, timedelta


class ScopeAmplificationError(RuntimeError):
    """Raised when a delegated exchange would widen authority beyond its parent."""
    pass


@dataclass(frozen=True)
class Credential:
    subject: str
    scopes: frozenset
    context: frozenset          # e.g. {"tenant:t-42", "purpose:pipeline-run-7"}
    not_before: datetime
    not_after: datetime
    parent_id: str | None = None


def exchange(parent: Credential, child_subject: str,
             requested_scopes: frozenset, requested_ttl: timedelta,
             requested_context: frozenset, now: datetime) -> Credential:
    # 1. Scope must be a subset of the parent's residual scope.
    if not requested_scopes <= parent.scopes:
        raise ScopeAmplificationError(
            f"scope escalation: {requested_scopes - parent.scopes} not held by parent"
        )

    # 2. Context claims must be preserved; a child may narrow but never drop.
    dropped = parent.context - requested_context
    if dropped:
        raise ScopeAmplificationError(
            f"context-claim drop: {dropped} present on parent, absent on child"
        )
    widened = requested_context - parent.context
    if widened:
        raise ScopeAmplificationError(
            f"context-claim widening: {widened} not authorized by parent"
        )

    # 3. Lifetime must be clamped to the parent's remaining lifetime, not reset.
    if now >= parent.not_after:
        raise ScopeAmplificationError(
            f"parent credential expired at {parent.not_after.isoformat()}"
        )
    proposed_expiry = now + requested_ttl
    if proposed_expiry > parent.not_after:
        # Clamp rather than reject: narrowing lifetime is always legal.
        proposed_expiry = parent.not_after

    return Credential(
        subject=child_subject,
        scopes=requested_scopes,
        context=requested_context,
        not_before=now,
        not_after=proposed_expiry,
        parent_id=f"{parent.subject}:{parent.not_after.isoformat()}",
    )


def verify_chain_closure(leaf: Credential, root: Credential) -> None:
    """Verify-time backstop: leaf must not outlive or out-scope its root."""
    if leaf.not_after > root.not_after:
        raise ScopeAmplificationError(
            f"leaf outlives root: {leaf.not_after.isoformat()} > {root.not_after.isoformat()}"
        )
    if not leaf.scopes <= root.scopes:
        raise ScopeAmplificationError(
            f"leaf scope exceeds root: {leaf.scopes - root.scopes}"
        )
    if not leaf.context <= root.context:
        raise ScopeAmplificationError(
            f"leaf context exceeds root: {leaf.context - root.context}"
        )
