# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-accept-a-delegated-credential-whose-issuer-key-rotated-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-accept-a-delegated-credential-whose-issuer-key-rotated-mid-chain.warrant.json
# Markdown SHA-256:   44f32b25ab9a408e6f81c3d042b3f343c8361c078340be4efd5021efeb1406ec
# Code AST SHA-256:   54553ec5c6b991b7d28a34da1f1a6848fc5916eb67c8c45d528cfce7713fd356
# Verified Classes:   DelegationChainError, KeyRecord, RotationProof, Credential, DidDocument
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when a delegated credential's authority cannot be established."""


@dataclass
class KeyRecord:
    key_id: str
    valid_from: float
    valid_until: Optional[float] = None


@dataclass
class RotationProof:
    old_key_id: str
    new_key_id: str
    rotated_at: float
    reason: str  # "scheduled" | "compromise" | "policy"
    dual_signed: bool


@dataclass
class Credential:
    issuer_did: str
    verification_method: str  # e.g. did:aaif:O#K1
    signed_at: float


@dataclass
class DidDocument:
    keys: dict = field(default_factory=dict)          # key_id -> KeyRecord
    rotations: list = field(default_factory=list)      # list[RotationProof]
    resolved_at: float = 0.0


def validate_delegated_credential(
    cred: Credential,
    doc: DidDocument,
    now: float,
    clock_skew: float = 30.0,
) -> str:
    """Return the authoritative key_id, or raise DelegationChainError."""
    key_id = cred.verification_method.split("#", 1)[-1]
    key = doc.keys.get(key_id)

    if key is None:
        raise DelegationChainError(
            f"verificationMethod {cred.verification_method} not in DID document"
        )

    # Cache staleness: a document resolved before a rotation we can see in
    # history means the resolver is operating on stale authority.
    if doc.resolved_at < cred.signed_at:
        raise DelegationChainError(
            "DID document resolved before credential signing time; "
            "cannot establish authoritative key state"
        )

    # Locate any rotation that retired this key.
    rotation = next(
        (r for r in doc.rotations if r.old_key_id == key_id), None
    )

    if rotation is None:
        # No rotation: key must still be within its validity window.
        if key.valid_until is not None and now > key.valid_until:
            raise DelegationChainError(
                f"key {key_id} expired at {key.valid_until}, now={now}"
            )
        return key_id

    # A rotation exists. It MUST be dual-signed to be trustworthy.
    if not rotation.dual_signed:
        raise DelegationChainError(
            f"rotation {key_id}->{rotation.new_key_id} lacks dual signature; "
            "treating as key substitution, not rotation"
        )

    # Ambiguity window: credential signed too close to rotation to resolve.
    if abs(cred.signed_at - rotation.rotated_at) < clock_skew:
        raise DelegationChainError(
            f"credential signed at {cred.signed_at} within skew of rotation "
            f"at {rotation.rotated_at}; authority ambiguous, refuse"
        )

    # Credential signed before rotation: valid only if rotation was not
    # compromise-triggered. A compromise rotation revokes pre-rotation
    # delegation authority retroactively.
    if cred.signed_at < rotation.rotated_at:
        if rotation.reason == "compromise":
            raise DelegationChainError(
                f"key {key_id} rotated for compromise at {rotation.rotated_at}; "
                f"credential signed at {cred.signed_at} is untrustworthy"
            )
        return key_id  # scheduled rotation, pre-rotation signature stands

    # Credential signed after rotation but still cites the old key.
    raise DelegationChainError(
        f"credential signed at {cred.signed_at} after key {key_id} was "
        f"rotated at {rotation.rotated_at}; signature does not bind to "
        "current authority"
    )
