# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-scope-token-exchange-across-aaif-trust-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-scope-token-exchange-across-aaif-trust-boundaries.warrant.json
# Markdown SHA-256:   33671cfcb7b334b816212513a2b96bdb52ac13e6048b02ef4f82b0a1469acd38
# Code AST SHA-256:   0245b3f8340530c07adf5c2155b12e6dd467611c8ceb93a1ec8cb50ccc4ad25a
# Verified Classes:   DelegationChainIncoherent, ActHop, DelegatedToken, VerifierConfig
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class DelegationChainIncoherent(RuntimeError):
    """Raised when a delegated-scope token's act stack cannot be
    resolved to a revocation-checkable root grant."""
    pass


@dataclass
class ActHop:
    jti: str
    nbf: int
    exp: int
    issuer: str


@dataclass
class DelegatedToken:
    jti: str
    scopes: frozenset
    act: list  # list[ActHop], act[0] is root
    nbf: int
    exp: int


@dataclass
class VerifierConfig:
    revocation_index_key: str = "act0_jti"  # or "leaf_jti"
    revocation_source: str = "push"        # or "pull"
    time_sensitive_scopes: frozenset = field(
        default_factory=lambda: frozenset({"write", "delete", "admin"})
    )
    max_nbf_skew: int = 0


def must_refuse_exchange(
    token: DelegatedToken,
    cfg: VerifierConfig,
    now: Optional[int] = None,
) -> bool:
    """
    Returns True iff the exchange MUST be refused per the
    monotonic-jti / root-revocation invariant.

    Refusal conditions (all must hold):
      1. act stack length >= 2 (multi-hop delegate)
      2. token.nbf > act[0].nbf (refresh occurred post-root-grant)
      3. revocation source is push AND indexed on leaf/act[0] jti
         (root jti unrecoverable from presentation)
      4. at least one requested scope is time-sensitive
    """
    if len(token.act) < 2:
        return False

    root = token.act[0]
    refreshed = token.nbf > root.nbf + cfg.max_nbf_skew
    if not refreshed:
        return False

    root_unresolvable = (
        cfg.revocation_source == "push"
        and cfg.revocation_index_key in ("leaf_jti", "act0_jti")
        and token.act[0].jti != token.jti  # act[0].jti was rewritten
    )
    # Detect rewritten act[0]: if the leaf's act[0].jti equals the
    # leaf jti, the refresh overwrote the root witness.
    rewritten = token.act[0].jti == token.jti

    time_sensitive = bool(token.scopes & cfg.time_sensitive_scopes)
    if not time_sensitive:
        return False

    return root_unresolvable or rewritten


def exchange_delegated_scope(
    token: DelegatedToken,
    requested_scopes: frozenset,
    cfg: VerifierConfig,
    now: Optional[int] = None,
) -> str:
    now = now if now is not None else int(time.time())

    if not requested_scopes <= token.scopes:
        raise DelegationChainIncoherent(
            f"scope escalation: requested {requested_scopes} "
            f"not subset of {token.scopes}"
        )

    if must_refuse_exchange(token, cfg, now):
        raise DelegationChainIncoherent(
            "refusing delegated-scope exchange: act stack root "
            f"jti={token.act[0].jti!r} is not revocation-resolvable "
            f"(leaf jti={token.jti!r}, nbf={token.nbf}, "
            f"root nbf={token.act[0].nbf}). Re-delegate from root "
            "holder to obtain a coherent witness chain."
        )

    if now < token.nbf or now > token.exp:
        raise DelegationChainIncoherent(
            f"token outside validity window: now={now} "
            f"nbf={token.nbf} exp={token.exp}"
        )

    return f"exchanged:{token.jti}:{sorted(requested_scopes)}"
