# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-agent-manifest-whose-verifiable-credential-chain-is-valid-but-whose-capability-attestation-i.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-agent-manifest-whose-verifiable-credential-chain-is-valid-but-whose-capability-attestation-i.warrant.json
# Markdown SHA-256:   8f71c1c317bb2aaa4c2598fd8687f4210710350b36eb982fbf0b8c7d0e0b802b
# Code AST SHA-256:   8c8333446ffe0f917d7b9d9bab1bf911c130aa60d7b57a1f515978eaa0937a37
# Verified Classes:   StaleAttestationEpoch, Manifest, IssuerStatus
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAttestationEpoch(RuntimeError):
    """Raised when a manifest's attestation epoch cannot be proven current."""
    pass


@dataclass
class Manifest:
    subject_did: str
    capability: str
    attestation_epoch: int
    key_version: int
    expiration_ts: float
    capability_floor: str  # signed fallback, e.g. "settlement.read"


@dataclass
class IssuerStatus:
    current_epoch: int
    key_version: int
    fetched_at: float
    max_age: float          # signed by issuer, NOT chosen by verifier
    doc_signature_ok: bool


def resolve_capability(
    manifest: Manifest,
    status: Optional[IssuerStatus],
    now: float,
    epoch_high_water: int,
    allowed_lag_for_capability: int,
) -> str:
    if not status or not status.doc_signature_ok:
        # Cannot prove currency. Degrade to signed floor, never assume current.
        return manifest.capability_floor

    if status.current_epoch < epoch_high_water:
        # Epoch rollback: status endpoint is lying or compromised.
        raise StaleAttestationEpoch(
            f"epoch rollback for {manifest.subject_did}: "
            f"status says {status.current_epoch}, high-water {epoch_high_water}"
        )

    if now - status.fetched_at > status.max_age:
        # Status doc older than the issuer permits; cache TTL is not ours to extend.
        return manifest.capability_floor

    if status.key_version < manifest.key_version:
        raise StaleAttestationEpoch(
            f"status key_version {status.key_version} predates "
            f"manifest key_version {manifest.key_version}"
        )

    if manifest.expiration_ts <= now:
        return manifest.capability_floor

    lag = status.current_epoch - manifest.attestation_epoch
    if lag > allowed_lag_for_capability:
        raise StaleAttestationEpoch(
            f"attestation epoch {manifest.attestation_epoch} lags issuer "
            f"epoch {status.current_epoch} by {lag} > allowed "
            f"{allowed_lag_for_capability} for capability {manifest.capability}"
        )

    return manifest.capability
