# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-agent-card-whose-attestation-chain-validates-cryptographically-but-whose-issuer-s-registry-e.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-agent-card-whose-attestation-chain-validates-cryptographically-but-whose-issuer-s-registry-e.warrant.json
# Markdown SHA-256:   a5af7de8b63eb9e0db044d5240f12a8a3f5f34aaadac0b01099ca17d2faf20a7
# Code AST SHA-256:   c22d0dc5cdd81f6fa20cea1d53129e0c279c7eb87e50e8232efa73a2e335632d
# Verified Classes:   CapabilityProvenanceError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CapabilityProvenanceError(RuntimeError):
    """Raised when a signed Agent Card asserts a capability the issuer
    was not authorized to attest at the chain's anchoring epoch."""

    def __init__(self, issuer: str, e_anchor: int, e_now: int, offending: list[str]):
        self.issuer = issuer
        self.e_anchor = e_anchor
        self.e_now = e_now
        self.offending = offending
        super().__init__(
            f"issuer={issuer} anchored at epoch {e_anchor} (now {e_now}) "
            f"lacks scope for {offending}"
        )


def verify_federated_card(card, registry, trusted_roots) -> set[str]:
    # 1-2: cryptographic + chain termination
    if not card.signature_verifies():
        raise CapabilityProvenanceError(card.issuer, card.e_anchor, registry.current_epoch(), ["<sig>"])
    if card.chain.root not in trusted_roots:
        raise CapabilityProvenanceError(card.issuer, card.e_anchor, registry.current_epoch(), ["<root>"])

    # 3: anchor must be the issuer's registration epoch, not latest
    e_anchor = card.chain.anchoring_epoch
    if e_anchor != registry.registration_epoch(card.issuer):
        raise CapabilityProvenanceError(card.issuer, e_anchor, registry.current_epoch(), ["<anchor>"])

    # 4: historical scope query -- fail closed if unavailable
    scope = registry.scope_at(card.issuer, e_anchor)
    if scope is None:
        raise CapabilityProvenanceError(card.issuer, e_anchor, registry.current_epoch(), ["<scope-unavailable>"])

    # 5: revocation window
    e_now = registry.current_epoch()
    revoked = registry.revocations_between(card.issuer, e_anchor, e_now)

    accepted = set()
    offending = []
    for cap in card.declared_capabilities:
        if cap in scope and cap not in revoked:
            accepted.add(cap)
        else:
            offending.append(cap)

    if offending:
        # partial acceptance is permitted; the offending set must be reported
        raise CapabilityProvenanceError(card.issuer, e_anchor, e_now, offending)

    return accepted
