# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-agent-credential-chains-to-an-aaif-root-that-has-rotated-its-signing-key-mid-presentation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-agent-credential-chains-to-an-aaif-root-that-has-rotated-its-signing-key-mid-presentation.warrant.json
# Markdown SHA-256:   881efd0192cfd75676215211db3c2ed3a06a3169d49dae1f42f99042f97fd3ef
# Code AST SHA-256:   8e0e5d5b5348899e8812eff9f02b0f6620149178d6eaaca73f9cb346cf9fba20
# Verified Classes:   ChainIndeterminateError, RootKeyState, Credential
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class ChainIndeterminateError(RuntimeError):
    """Raised when a federated credential chain crosses an AAIF root rotation
    that cannot be resolved to VALID or INVALID from chain material alone."""
    pass


@dataclass
class RootKeyState:
    key_id: str
    deactivated_at: datetime | None
    grace_window: timedelta


@dataclass
class Credential:
    issuance: datetime
    expiration: datetime
    chain_anchor: str | None  # proof.chainAnchor matching current root key id


def validate_rotation_boundary(
    cred: Credential,
    root_key: RootKeyState,
    current_root_key_id: str,
) -> str:
    """Returns 'VALID' or raises ChainIndeterminateError.

    A rotation-crossing chain is VALID only if the credential was issued before
    deactivation AND expires within the grace window, OR carries a chainAnchor
    matching the current root key. Otherwise the RP must halt.
    """
    if cred.chain_anchor == current_root_key_id:
        return "VALID"

    if root_key.deactivated_at is None:
        return "VALID"

    issued_before = cred.issuance < root_key.deactivated_at
    expires_within_grace = cred.expiration <= (
        root_key.deactivated_at + root_key.grace_window
    )

    if issued_before and expires_within_grace:
        return "VALID"

    raise ChainIndeterminateError(
        f"chain crosses AAIF root rotation at {root_key.deactivated_at.isoformat()} "
        f"(key {root_key.key_id}); credential issuance={cred.issuance.isoformat()} "
        f"expiration={cred.expiration.isoformat()} "
        f"grace_window={root_key.grace_window}; "
        f"issued_before={issued_before} expires_within_grace={expires_within_grace}; "
        f"re-attestation required against current root {current_root_key_id}"
    )


def handle_presentation(cred: Credential, root_key: RootKeyState, current_id: str) -> dict:
    try:
        status = validate_rotation_boundary(cred, root_key, current_id)
        return {"status": status}
    except ChainIndeterminateError as e:
        # Structured, agent-visible challenge — not a silent 401.
        return {
            "status": "INDETERMINATE_CHAIN",
            "challenge": "re_attest",
            "reason": str(e),
        }
