# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-trust-anchor-whose-validity-interval-was-resolved-against-the-wrong-clock-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-trust-anchor-whose-validity-interval-was-resolved-against-the-wrong-clock-epoch.warrant.json
# Markdown SHA-256:   fafdc7255cbfdd6e9945e74ffa23845976acdeb9d134484363f5b22c9aaf1825
# Code AST SHA-256:   81e4f89f309a4e8566b431cffb9ff64286d80dcc5f46e2558893d57d7d4a3a14
# Verified Classes:   TrustAnchorClockSkewError, TrustAnchor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class TrustAnchorClockSkewError(RuntimeError):
    """Raised when a federated trust anchor's validity cannot be decided
    under the relying instance's clock within the protocol tolerance."""


@dataclass
class TrustAnchor:
    not_before: float          # issuer-clock epoch seconds
    not_after: float           # issuer-clock epoch seconds
    issuer_clock_reading: float  # issuer's own clock at mint time
    issuer_clock_uncertainty: float  # issuer's declared |delta| bound


def validate_anchor(
    anchor: TrustAnchor,
    now_local: float,
    tolerance_tau: float,
) -> str:
    """
    Returns 'accept', 'reject', or 'defer'.
    Raises TrustAnchorClockSkewError when the interval is too narrow to
    absorb the declared skew (no valid operating region).
    """
    interval_width = anchor.not_after - anchor.not_before
    if interval_width < 2 * tolerance_tau:
        raise TrustAnchorClockSkewError(
            f"anchor interval {interval_width:.3f}s narrower than 2*tau="
            f"{2 * tolerance_tau:.3f}s; no skew-tolerant operating region exists"
        )

    # Estimate skew between relying clock and issuer clock at mint time.
    skew = now_local - anchor.issuer_clock_reading
    if abs(skew) > tolerance_tau:
        raise TrustAnchorClockSkewError(
            f"clock skew {skew:.3f}s exceeds tolerance {tolerance_tau:.3f}s; "
            f"validity verdict is undefined"
        )

    # Project local now into issuer frame.
    now_issuer_frame = now_local - skew

    if now_issuer_frame < anchor.not_before - tolerance_tau:
        return "reject"  # not yet valid under any skew <= tau
    if now_issuer_frame > anchor.not_after + tolerance_tau:
        return "reject"  # expired under any skew <= tau

    # Tolerance bands: cannot decide locally, must defer to issuer liveness.
    if (
        anchor.not_before - tolerance_tau
        <= now_issuer_frame
        <= anchor.not_before + tolerance_tau
    ):
        return "defer"
    if (
        anchor.not_after - tolerance_tau
        <= now_issuer_frame
        <= anchor.not_after + tolerance_tau
    ):
        return "defer"

    return "accept"
