# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-brokered-capability-attestation-that-was-valid-at-issuance-but-whose-policy-context-has-since-been-revoked-upst.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-brokered-capability-attestation-that-was-valid-at-issuance-but-whose-policy-context-has-since-been-revoked-upst.warrant.json
# Markdown SHA-256:   fcea6296716347634aaf4d564a46429b17dfe0f82cfcda32ef13d3b8323f61c8
# Code AST SHA-256:   bd83813be6decd624d0f0c4e5e5ddd4c19d9ebb540f0024e6bc308150f82abbb
# Verified Classes:   AttestationPostureError, Posture, BrokeredCapabilityAttestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum


class AttestationPostureError(RuntimeError):
    """Raised when a brokered capability attestation cannot be accepted under any sound posture."""


class Posture(Enum):
    SHORT_LIVED = "short_lived"
    REVOCATION_AWARE = "revocation_aware"
    DEREFERENCE_AT_DECISION = "dereference_at_decision"
    UNGUARDED = "unguarded"  # must never be accepted


@dataclass(frozen=True)
class BrokeredCapabilityAttestation:
    bca_id: str
    fp_id: str
    capability: str
    policy_ref: str
    issued_at: datetime
    not_after: datetime
    revocation_endpoint: str | None
    revocation_check_interval: timedelta | None
    policy_ref_dereferenceable: bool


def classify_and_validate(
    bca: BrokeredCapabilityAttestation,
    now: datetime,
    max_staleness: timedelta,
) -> Posture:
    """Classify the attestation's posture and reject the unguarded fourth posture.

    Returns the posture under which the RPI may proceed. Raises
    AttestationPostureError if the attestation is expired, not yet valid,
    or falls into the unguarded posture (long-lived, no revocation channel,
    no dereferenceable policy reference).
    """
    if now < bca.issued_at:
        raise AttestationPostureError(
            f"BCA {bca.bca_id} not yet valid: issued_at={bca.issued_at.isoformat()} now={now.isoformat()}"
        )
    if now >= bca.not_after:
        raise AttestationPostureError(
            f"BCA {bca.bca_id} expired at {bca.not_after.isoformat()}"
        )

    window = bca.not_after - bca.issued_at

    # Posture 1: short-lived attestation bounds staleness by construction.
    if window <= max_staleness:
        return Posture.SHORT_LIVED

    # Posture 2: revocation channel with a bounded check interval.
    if bca.revocation_endpoint and bca.revocation_check_interval is not None:
        if bca.revocation_check_interval > max_staleness:
            raise AttestationPostureError(
                f"BCA {bca.bca_id} revocation_check_interval "
                f"{bca.revocation_check_interval} exceeds max_staleness {max_staleness}"
            )
        return Posture.REVOCATION_AWARE

    # Posture 3: dereferenceable policy reference.
    if bca.policy_ref_dereferenceable:
        return Posture.DEREFERENCE_AT_DECISION

    # The unguarded fourth posture: long-lived, no revocation, no dereference.
    raise AttestationPostureError(
        f"BCA {bca.bca_id} is unguarded: window={window} exceeds max_staleness="
        f"{max_staleness}, no revocation_endpoint, policy_ref {bca.policy_ref!r} "
        f"is not dereferenceable. Refusing to authorize."
    )


def effective_cache_ttl(posture: Posture, bca: BrokeredCapabilityAttestation, now: datetime) -> timedelta:
    """Cache TTL must never outlive the attestation window or the revocation check interval."""
    residual = bca.not_after - now
    if posture is Posture.REVOCATION_AWARE and bca.revocation_check_interval is not None:
        return min(residual, bca.revocation_check_interval)
    if posture is Posture.SHORT_LIVED:
        return residual
    if posture is Posture.DEREFERENCE_AT_DECISION:
        return timedelta(0)  # re-dereference every decision
    raise AttestationPostureError(f"no cache TTL defined for posture {posture}")
