# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-dereference-a-federated-agent-trust-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-dereference-a-federated-agent-trust-anchor.warrant.json
# Markdown SHA-256:   2d634bc0d707530f0290e97ef2551535c1b69e7006b9ba112104ab5fdddaf3e7
# Code AST SHA-256:   e4aa754ad034edea99474302d7f2d367ccea10ab89d53c852443297898439a3f
# Verified Classes:   AuthorityCycleError, Anchor, Attestation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class AuthorityCycleError(RuntimeError):
    """Raised when a federated anchor's load-bearing signature set forms an authority cycle."""


@dataclass(frozen=True)
class Anchor:
    subject: str
    identity_authority: str
    countersigned_by: tuple[str, ...] = field(default_factory=tuple)


@dataclass(frozen=True)
class Attestation:
    subject: str
    issuer: str
    claims_identity_authority: bool = False


def _authority_edges(anchor: Anchor, attestations: Iterable[Attestation]) -> dict[str, set[str]]:
    edges: dict[str, set[str]] = {anchor.identity_authority: set()}
    for att in attestations:
        if att.subject != anchor.subject:
            continue
        edges.setdefault(att.issuer, set())
        # An attestation that asserts identity authority is out-of-scope for the
        # reputation channel and must not be used to close a trust cycle.
        if att.claims_identity_authority:
            edges[att.issuer].add(anchor.identity_authority)
        for co in anchor.countersigned_by:
            edges.setdefault(co, set())
            edges[co].add(att.issuer)
    return edges


def _has_cycle(edges: dict[str, set[str]]) -> bool:
    WHITE, GREY, BLACK = 0, 1, 2
    color: dict[str, int] = {n: WHITE for n in edges}

    def visit(n: str) -> bool:
        color[n] = GREY
        for m in edges.get(n, ()):
            if color.get(m, WHITE) == GREY:
                return True
            if color.get(m, WHITE) == WHITE and visit(m):
                return True
        color[n] = BLACK
        return False

    return any(color[n] == WHITE and visit(n) for n in list(edges))


def admit(
    anchor: Anchor,
    attestations: Iterable[Attestation],
    *,
    joint_authority_records: frozenset[tuple[str, str]] = frozenset(),
) -> bool:
    edges = _authority_edges(anchor, attestations)
    if not _has_cycle(edges):
        return True
    # A cycle is admissible only if a pre-registered joint-authority record
    # covers every edge in the cycle. We approximate coverage by checking the
    # unordered pair of the anchor's authority and each countersigner.
    pairs = {
        frozenset((anchor.identity_authority, co))
        for co in anchor.countersigned_by
    }
    covered = all(
        frozenset(p) in {frozenset(r) for r in joint_authority_records}
        for p in pairs
    )
    if covered:
        return True
    raise AuthorityCycleError(
        f"anchor for {anchor.subject!r} forms an authority cycle over "
        f"{sorted(edges)} with no covering joint-authority record; "
        f"refusing dereference"
    )
