# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-attestation-whose-issuer-chain-re-enters-its-own-trust-domain.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-attestation-whose-issuer-chain-re-enters-its-own-trust-domain.warrant.json
# Markdown SHA-256:   4c5a70987cdea8151d85769e1d06f9146fcb6e89c14b824b918cfbf81cd28b83
# Code AST SHA-256:   837eafa649cd6dfdefd9a19059e22b0962b283561352c7aad9f6ac9010b0243a
# Verified Classes:   ReEntryWithoutPin, NonMonotonicAttenuation, Hop, Chain
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReEntryWithoutPin(RuntimeError):
    """Raised when a delegation chain re-enters the verifier's trust domain
    without an explicit re-entry pin and intersect proof."""
    pass


class NonMonotonicAttenuation(RuntimeError):
    """Raised when a hop widens scope instead of narrowing it."""
    pass


@dataclass
class Hop:
    issuer_domain: str
    issuer_key: str
    scope: frozenset
    # If this hop re-enters a domain, it must carry a pin naming the exact key
    # and an intersect proof showing scope(child) <= scope(original_exit).
    reentry_pin: Optional[str] = None
    intersect_proof: Optional[frozenset] = None  # scope at the original exit


@dataclass
class Chain:
    # Ordered root -> leaf
    hops: list = field(default_factory=list)


def verify_delegation(chain: Chain, verifier_domain: str,
                      pinned_reentry_keys: dict) -> bool:
    visited_domains = set()
    exited_verifier_domain = False
    scope_at_exit = None

    for i, hop in enumerate(chain.hops):
        # Monotonic attenuation check against parent hop.
        if i > 0:
            parent = chain.hops[i - 1]
            if not hop.scope.issubset(parent.scope):
                raise NonMonotonicAttenuation(
                    f"hop {i} scope {set(hop.scope)} not subset of "
                    f"hop {i-1} scope {set(parent.scope)}"
                )

        # Detect exit from verifier domain.
        if hop.issuer_domain != verifier_domain and not exited_verifier_domain:
            if verifier_domain in visited_domains:
                exited_verifier_domain = True
                scope_at_exit = hop.scope

        # Detect re-entry into verifier domain after having exited.
        if hop.issuer_domain == verifier_domain and exited_verifier_domain:
            pinned = pinned_reentry_keys.get(hop.issuer_key)
            if pinned is None or hop.reentry_pin != hop.issuer_key:
                raise ReEntryWithoutPin(
                    f"chain re-enters {verifier_domain} at hop {i} "
                    f"(key={hop.issuer_key}) without a matching pin"
                )
            if hop.intersect_proof is None or not hop.scope.issubset(hop.intersect_proof):
                raise ReEntryWithoutPin(
                    f"re-entry at hop {i} lacks intersect proof bounding scope "
                    f"to original exit {set(scope_at_exit or frozenset())}"
                )

        visited_domains.add(hop.issuer_domain)

    return True
