# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-when-a-delegated-credential-chain-crosses-a-key-rotation-boundary-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-when-a-delegated-credential-chain-crosses-a-key-rotation-boundary-mid-task.warrant.json
# Markdown SHA-256:   a6645408f6be5bb693bc877be0886b2400a6f4c794dae6eba5af6034c3525117
# Code AST SHA-256:   83d8fa6b518af7fd32fa281b5db35dc476b4fbff18950c6c152f53dc3eab2a1d
# Verified Classes:   ChainAttestationError, SupersessionKind, IssuerState, CachedChain
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ChainAttestationError(RuntimeError):
    """Raised when a cached delegated chain can no longer be presented as live authority."""


class SupersessionKind(Enum):
    NONE = "none"
    ROTATED_SAME_SCOPE = "rotated_same_scope"
    NARROWED = "narrowed"          # scope reduced: invalidates cache immediately
    REVOKED = "revoked"


@dataclass(frozen=True)
class IssuerState:
    key_id: str
    supersession: SupersessionKind
    scope_superset_of_cached: bool  # False if the re-issued warrant narrowed scope
    reachable: bool


@dataclass(frozen=True)
class CachedChain:
    key_id: str
    snapshot_at: datetime
    max_chain_age: timedelta


def must_reattest(chain: CachedChain, issuer: IssuerState, now: datetime) -> bool:
    """
    Decide whether the executing agent must re-derive its chain before presenting
    it downstream. Returns True if re-attestation is mandatory.
    """
    if not issuer.reachable:
        # Cannot confirm live authority. Per invariant 4, this is not "proceed".
        raise ChainAttestationError(
            f"issuer {issuer.key_id} unreachable; cached chain cannot be presented as live"
        )

    if issuer.key_id != chain.key_id:
        # Issuer already rotated to a new key we have not adopted.
        return True

    if issuer.supersession is SupersessionKind.REVOKED:
        raise ChainAttestationError(
            f"chain under {chain.key_id} revoked; presentation forbidden"
        )

    if issuer.supersession is SupersessionKind.NARROWED or not issuer.scope_superset_of_cached:
        # The non-obvious case: signatures still verify against the old key,
        # but the delegator has reduced our authority. Cached chain is a scope bypass.
        raise ChainAttestationError(
            f"scope narrowed under {chain.key_id}; cached chain defeats delegator intent"
        )

    if issuer.supersession is SupersessionKind.ROTATED_SAME_SCOPE:
        return True  # same authority, new key: re-derive, safe to continue

    if now - chain.snapshot_at > chain.max_chain_age:
        return True  # staleness window exceeded

    return False


def present_chain(chain: CachedChain, issuer: IssuerState, now: datetime) -> str:
    if must_reattest(chain, issuer, now):
        # Caller must fetch fresh key material and re-derive before retrying.
        raise ChainAttestationError(
            f"re-attestation required for {chain.key_id} before downstream presentation"
        )
    return f"presenting cached chain {chain.key_id} (verified live)"
