# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-did-resolution-staleness-as-an-authentication-failure-rather-than-a-retryable-transport-error-in-a2a-v1-0-han.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-did-resolution-staleness-as-an-authentication-failure-rather-than-a-retryable-transport-error-in-a2a-v1-0-han.warrant.json
# Markdown SHA-256:   ef838de1afa8658f3a2047460ccc2adfadc22e4d873dad7a49de6279fc048257
# Code AST SHA-256:   f9203b36b978446073c4d1839b28f879345dc9c3e16aebae56a14d898b6de4cd
# Verified Classes:   StaleResolutionAuthError, KeyCompromiseError, TrustDowngradeForbidden, ResolutionFreshness, ResolvedDid, VerificationResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class StaleResolutionAuthError(RuntimeError):
    """Raised when signature verification fails against a cached/stale DID document.

    This is an authentication integrity event, NOT a retryable transport error.
    It must halt the handshake and trigger exactly one cache-bypassing re-resolve.
    """


class KeyCompromiseError(RuntimeError):
    """Raised when signature verification fails against a FRESH DID document.

    Indicates key compromise or misconfiguration. Zero retries. Security alert.
    """


class TrustDowngradeForbidden(RuntimeError):
    """Raised when a fallback to a pinned Agent Card is attempted without
    any fresh, verified resolution of the peer in the current session."""


class ResolutionFreshness(Enum):
    FRESH = "fresh"
    STALE = "stale"
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class ResolvedDid:
    did: str
    did_document: dict
    freshness: ResolutionFreshness
    retrieved_at: float
    version_id: str | None


@dataclass(frozen=True)
class VerificationResult:
    ok: bool
    error: str | None


def verify_signature(resolved: ResolvedDid, signed_payload: bytes, signature: bytes) -> VerificationResult:
    # Real implementation extracts verificationMethod from resolved.did_document
    # and checks the signature. Here we simulate a failure.
    return VerificationResult(ok=False, error="signature mismatch")


def authenticate_peer(
    did: str,
    signed_payload: bytes,
    signature: bytes,
    resolve_fn,
    session_fresh_resolution: bool,
) -> ResolvedDid:
    resolved = resolve_fn(did)

    result = verify_signature(resolved, signed_payload, signature)
    if result.ok:
        return resolved

    if resolved.freshness is ResolutionFreshness.FRESH:
        # Fresh doc + bad signature => compromise/misconfig. No retry, no downgrade.
        raise KeyCompromiseError(
            f"Signature verification failed against FRESH DID document for {did}; "
            f"treat as key compromise. version_id={resolved.version_id}"
        )

    if resolved.freshness is ResolutionFreshness.STALE:
        # Stale doc + bad signature => integrity event. Attempt exactly one
        # cache-bypassing re-resolve; never enter a generic retry loop.
        retry_resolved = resolve_fn(did, bypass_cache=True)
        if retry_resolved.freshness is not ResolutionFreshness.FRESH:
            raise StaleResolutionAuthError(
                f"Cache-bypassing re-resolve for {did} still returned non-fresh document; "
                f"cannot establish authentication. Halting handshake."
            )
        retry_result = verify_signature(retry_resolved, signed_payload, signature)
        if not retry_result.ok:
            raise KeyCompromiseError(
                f"Signature failed even against freshly re-resolved document for {did}; "
                f"treat as compromise."
            )
        return retry_resolved

    # Freshness unknown: cannot distinguish stale from compromise. Fail closed.
    raise StaleResolutionAuthError(
        f"Resolution metadata for {did} lacks freshness signal; "
        f"refusing to retry or downgrade. Fail closed."
    )


def fallback_to_pinned_card(session_fresh_resolution: bool, did: str) -> None:
    if not session_fresh_resolution:
        raise TrustDowngradeForbidden(
            f"Attempted trust downgrade for {did} without any fresh verified "
            f"resolution in this session; integrity fallback forbidden."
        )
    # proceed with pinned card for liveness-only fallback
