# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-agent-card-whose-credential-chain-validates-to-a-stale-issuer-key.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-agent-card-whose-credential-chain-validates-to-a-stale-issuer-key.warrant.json
# Markdown SHA-256:   a041fab5e51aa4dff3c2da725781e0c1af6f5a0d483a7ba86976703cc73bea34
# Code AST SHA-256:   e0f35af979dba49a7ff972d75ac1695f88dba40007cd789e024e44231f04e2e4
# Verified Classes:   StaleIssuerKeyError, Credential, KeySetSnapshot
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleIssuerKeyError(RuntimeError):
    """Raised when a federated credential cannot be proven current against the issuer's key state."""
    pass


@dataclass(frozen=True)
class Credential:
    jti: str
    issuer: str
    signing_key_id: str
    iat: float          # issued-at, epoch seconds
    exp: float          # expiry, epoch seconds


@dataclass(frozen=True)
class KeySetSnapshot:
    issuer: str
    fetched_at: float
    active_key_ids: frozenset
    superseded_key_ids: frozenset
    last_rotation_at: float


def admit_federated_credential(
    cred: Credential,
    snapshot: KeySetSnapshot,
    now: float,
    propagation_sla: float,
    clock_skew_margin: float,
    refresh_fn,  # callable(issuer) -> KeySetSnapshot, synchronous live fetch
) -> KeySetSnapshot:
    if cred.issuer != snapshot.issuer:
        raise StaleIssuerKeyError(
            f"snapshot issuer {snapshot.issuer!r} does not match credential issuer {cred.issuer!r}"
        )

    # Expiry / not-before band.
    if not (cred.iat - clock_skew_margin <= now <= cred.exp):
        raise StaleIssuerKeyError(f"credential {cred.jti} outside validity window")

    # The signing key must be active, not merely historically verifiable.
    if cred.signing_key_id in snapshot.superseded_key_ids:
        raise StaleIssuerKeyError(
            f"credential {cred.jti} signed by superseded key {cred.signing_key_id}"
        )
    if cred.signing_key_id not in snapshot.active_key_ids:
        raise StaleIssuerKeyError(
            f"credential {cred.jti} signing key {cred.signing_key_id} absent from issuer key set"
        )

    # The core invariant: the snapshot must postdate both issuance and the last rotation,
    # with margin for propagation lag and clock skew. Otherwise the credential is unresolved.
    freshness_floor = max(cred.iat, snapshot.last_rotation_at) + propagation_sla + clock_skew_margin
    if snapshot.fetched_at < freshness_floor:
        # Cannot prove the key was current at a time we observed; force a live refresh.
        live = refresh_fn(cred.issuer)
        if live.fetched_at < freshness_floor:
            raise StaleIssuerKeyError(
                f"credential {cred.jti} unresolved: live snapshot {live.fetched_at} "
                f"predates freshness floor {freshness_floor}"
            )
        if cred.signing_key_id in live.superseded_key_ids or cred.signing_key_id not in live.active_key_ids:
            raise StaleIssuerKeyError(
                f"credential {cred.jti} rejected after refresh: key {cred.signing_key_id} no longer active"
            )
        return live

    return snapshot
