# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-mint-a-downstream-aaif-credential-when-the-upstream-chain-contains-a-re-delegation-hop-whose-scope-wa.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-mint-a-downstream-aaif-credential-when-the-upstream-chain-contains-a-re-delegation-hop-whose-scope-wa.warrant.json
# Markdown SHA-256:   5c466ed809a3da1ff5d94b9432dfdd171ee613700d9510ba9d9fc77aad4e80c6
# Code AST SHA-256:   5e47530e3b11b275d4f30b45b3cd3791a03349004f50e428c4c7f5c346fcbd93
# Verified Classes:   UnverifiableNarrowingError, ScopeNarrowing, MintContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnverifiableNarrowingError(RuntimeError):
    """Raised when a downstream credential would be minted from a
    policy-narrowed upstream scope whose policy reference the minting
    instance cannot resolve, verify, or bound by freshness."""


@dataclass(frozen=True)
class ScopeNarrowing:
    policy_ref: Optional[str]        # e.g. "aaif:policy:...@sha256:..."
    scope_digest: Optional[str]      # signed digest over concrete scope, or None
    narrowed_at: int                 # epoch seconds
    concrete_scope: frozenset[str]


@dataclass(frozen=True)
class MintContext:
    can_resolve: bool                # reference resolvable & evaluable locally
    is_relying_party: bool           # trust root designates us for this namespace
    max_reference_age: int           # seconds; 0 means "no bound -> refuse"
    now: int


def assert_mintable(narrowing: ScopeNarrowing, ctx: MintContext) -> None:
    # Inline scope (no reference) is always verifiable data.
    if narrowing.policy_ref is None:
        return

    # A signed digest over the concrete scope makes the reference
    # non-load-bearing: we verify the data, not the conclusion.
    if narrowing.scope_digest is not None:
        return

    # Otherwise the reference is load-bearing. It must be resolvable
    # AND we must be an authorized relying party with a freshness bound.
    if not ctx.can_resolve:
        raise UnverifiableNarrowingError(
            f"policy reference {narrowing.policy_ref!r} is unresolvable; "
            "refusing to mint downstream credential from unverified premise"
        )
    if not ctx.is_relying_party:
        raise UnverifiableNarrowingError(
            f"instance is not a designated relying party for "
            f"{narrowing.policy_ref!r}; cannot attest to its narrowing"
        )
    if ctx.max_reference_age <= 0:
        raise UnverifiableNarrowingError(
            "no freshness bound configured for policy references; "
            "stale-snapshot risk is unbounded"
        )
    age = ctx.now - narrowing.narrowed_at
    if age > ctx.max_reference_age:
        raise UnverifiableNarrowingError(
            f"policy reference {narrowing.policy_ref!r} is {age}s old, "
            f"exceeds bound of {ctx.max_reference_age}s"
        )


def mint_downstream(narrowing: ScopeNarrowing, ctx: MintContext,
                    requested: frozenset[str]) -> frozenset[str]:
    assert_mintable(narrowing, ctx)
    if not requested <= narrowing.concrete_scope:
        raise UnverifiableNarrowingError(
            "requested scope exceeds stated upstream scope"
        )
    return requested
