# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-cross-domain-trust-anchor-whose-signing-key-rotates-mid-resolution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-cross-domain-trust-anchor-whose-signing-key-rotates-mid-resolution.warrant.json
# Markdown SHA-256:   16a315537209c81cfac47d1732a7c75f2732c00bd584a09cadc9d602cbaa2c68
# Code AST SHA-256:   f28115854610f87d83d4d7c0cef2c95e00f16d7df523b70690379ddbb4641551
# Verified Classes:   TrustAnchorContinuityError, Anchor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class TrustAnchorContinuityError(RuntimeError):
    """Raised when a cached trust anchor cannot justify the presented credential."""


FRESHNESS_FLOOR_SECONDS = 30.0
MAX_REANCHOR_ATTEMPTS = 1


@dataclass
class Anchor:
    kids: set[str]
    fetched_at: float
    not_before: float


def resolve_credential(
    anchor: Anchor,
    presented_kid: str,
    credential_iat: float,
    refetch_anchor,
    overlap_seconds: float,
    now: float | None = None,
) -> Anchor:
    now = time.time() if now is None else now
    age = now - anchor.fetched_at

    if presented_kid in anchor.kids:
        # Continuity check: issuer may have rotated past what we hold.
        if credential_iat - anchor.not_before > overlap_seconds:
            raise TrustAnchorContinuityError(
                f"credential iat={credential_iat} postdates anchor not_before="
                f"{anchor.not_before} by more than overlap={overlap_seconds}; "
                "anchor is discontinuous, refusing to validate"
            )
        return anchor

    # kid miss: recoverable only if the anchor is fresh enough to be a lag artifact.
    if age <= FRESHNESS_FLOOR_SECONDS:
        for _ in range(MAX_REANCHOR_ATTEMPTS):
            refreshed = refetch_anchor()
            if presented_kid in refreshed.kids:
                return refreshed
        raise TrustAnchorContinuityError(
            f"kid={presented_kid} absent after re-anchor; treat as untrusted"
        )

    raise TrustAnchorContinuityError(
        f"kid={presented_kid} absent and anchor age={age:.1f}s exceeds "
        f"freshness floor={FRESHNESS_FLOOR_SECONDS}s; refusing to re-anchor "
        "on a stalled cache"
    )
