# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-credential-whose-scope-chain-is-transitively-valid-but-whose-issuer-set-intersection-is-empty.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-credential-whose-scope-chain-is-transitively-valid-but-whose-issuer-set-intersection-is-empty.warrant.json
# Markdown SHA-256:   d2c75a3daad41cc1d1bf2b58304f2e078cb4646594c67c4d5526f21aa4d23121
# Code AST SHA-256:   af2f6a38070453765de1eb4d4f5f255cb53909075e32cb0aedf312a9da73d2aa
# Verified Classes:   EmptyAnchorIntersectionError, Credential, ChainValidation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class EmptyAnchorIntersectionError(RuntimeError):
    """Raised when a delegation chain is hop-valid but no acceptable
    root-issuer set jointly anchors the terminal scope."""


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject: str
    scope: str
    counter_issuer: str | None = None
    parent_issuer: str | None = None  # None => this credential is a root


@dataclass
class ChainValidation:
    chain: list[Credential]
    terminal_scope: str
    required_anchors: FrozenSet[str]
    acceptable_roots: dict[str, FrozenSet[str]] = field(default_factory=dict)

    def _root_issuers(self) -> FrozenSet[str]:
        return frozenset(c.issuer for c in self.chain if c.parent_issuer is None)

    def _all_issuers(self) -> FrozenSet[str]:
        out = set()
        for c in self.chain:
            out.add(c.issuer)
            if c.counter_issuer:
                out.add(c.counter_issuer)
        return frozenset(out)

    def validate(self) -> None:
        roots = self._root_issuers()
        present = self._all_issuers()

        # Required anchors must be roots, not merely present as counter-issuers.
        anchored = self.required_anchors & roots
        if not self.required_anchors <= anchored:
            missing = self.required_anchors - anchored
            # Distinguish "absent entirely" from "present but wrong position".
            mispositioned = missing & present
            raise EmptyAnchorIntersectionError(
                f"scope={self.terminal_scope!r} requires anchors "
                f"{sorted(self.required_anchors)}; roots={sorted(roots)}; "
                f"missing={sorted(missing)}; "
                f"present-but-not-root={sorted(mispositioned)}"
            )

        # Each root must be policy-acceptable for the terminal scope.
        for r in self.required_anchors:
            allowed = self.acceptable_roots.get(r, frozenset())
            if self.terminal_scope not in allowed:
                raise EmptyAnchorIntersectionError(
                    f"root issuer {r!r} not acceptable for scope "
                    f"{self.terminal_scope!r}"
                )


def authorize(chain: list[Credential], terminal_scope: str,
              required_anchors: FrozenSet[str],
              acceptable_roots: dict[str, FrozenSet[str]]) -> None:
    ChainValidation(chain, terminal_scope, required_anchors,
                    acceptable_roots).validate()
