# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-chain-exceeds-its-own-verification-depth-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-chain-exceeds-its-own-verification-depth-budget.warrant.json
# Markdown SHA-256:   aef968ac9d4b8f25a1e8cd25b8fda1b2750eb45e5c8b8b8ffb1b5d4d94aa9efb
# Code AST SHA-256:   7613ae2b1392da8038d5524a43d3322df7fbf18c3b06baede9ceda66c9f5e180
# Verified Classes:   AAIFRefusal, Verdict, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class AAIFRefusal(RuntimeError):
    """Raised when a delegated credential cannot be fully verified within budget."""
    def __init__(self, reason: str, detail: str):
        self.reason = reason
        self.detail = detail
        super().__init__(f"{reason}: {detail}")


class Verdict(Enum):
    ACCEPT = "accept"
    DEPTH_EXCEEDED = "depth_exceeded"
    REVOCATION_UNKNOWN = "revocation_unknown"
    SCOPE_WIDENED = "scope_widened"
    CHAIN_TRUNCATED = "chain_truncated"


@dataclass
class Hop:
    issuer: str
    subject: str
    scope: frozenset
    revocation_fresh: bool
    parent_named: bool


def verify_chain(chain: list[Hop], depth_budget: int, freshness_required: bool = True) -> Verdict:
    """Verify an AAIF delegation chain. Returns a Verdict; never returns a soft 'partial'."""
    if len(chain) > depth_budget:
        raise AAIFRefusal(
            "DEPTH_EXCEEDED",
            f"chain length {len(chain)} exceeds verifier depth budget {depth_budget}",
        )

    prev_scope: frozenset | None = None
    for i, hop in enumerate(chain):
        if not hop.parent_named:
            raise AAIFRefusal(
                "CHAIN_TRUNCATED",
                f"hop {i} ({hop.issuer}->{hop.subject}) does not name its parent issuer",
            )
        if freshness_required and not hop.revocation_fresh:
            raise AAIFRefusal(
                "REVOCATION_UNKNOWN",
                f"hop {i} ({hop.issuer}->{hop.subject}) revocation status stale or unfetchable",
            )
        if prev_scope is not None and not hop.scope.issubset(prev_scope):
            raise AAIFRefusal(
                "SCOPE_WIDENED",
                f"hop {i} scope {set(hop.scope)} is not a subset of parent {set(prev_scope)}",
            )
        prev_scope = hop.scope

    return Verdict.ACCEPT


def accept_or_refuse(chain: list[Hop], depth_budget: int) -> bool:
    """Total decision function: any refusal class is a hard refusal, never a fallback-accept."""
    try:
        verdict = verify_chain(chain, depth_budget)
    except AAIFRefusal:
        # Refusal is terminal. Do NOT retry with same chain; escalate or re-issue.
        return False
    return verdict is Verdict.ACCEPT
