# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-card-whose-did-controller-has-rotated-out-from-under-the-credential-s-issuance-window.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-card-whose-did-controller-has-rotated-out-from-under-the-credential-s-issuance-window.warrant.json
# Markdown SHA-256:   d37a9cbb061d32146b1220c4012ef528c788896f212e3c264f35bab0239c57a4
# Code AST SHA-256:   b0901635f5cbab454784260e28f8c62cd991a07b3ae8ee125e17f97169cd3c96
# Verified Classes:   TrustAnchorRotationError, VerifiableCredential, DidDocumentVersion, RotationPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional


class TrustAnchorRotationError(RuntimeError):
    """Raised when a credential's authority cannot be bound to a single DID document version."""


@dataclass(frozen=True)
class VerifiableCredential:
    issuer_did: str
    issuance: datetime
    expiration: Optional[datetime]  # None == unbounded
    signing_key_id: str
    claims_hash: str


@dataclass(frozen=True)
class DidDocumentVersion:
    did: str
    effective_at: datetime
    verification_methods: frozenset[str]
    controllers: frozenset[str]


@dataclass(frozen=True)
class RotationPolicy:
    max_interval: timedelta


def _resolve_at(did: str, when: datetime, history: list[DidDocumentVersion]) -> DidDocumentVersion:
    candidates = [d for d in history if d.did == did and d.effective_at <= when]
    if not candidates:
        raise TrustAnchorRotationError(
            f"no DID document version for {did} effective at or before {when.isoformat()}"
        )
    return max(candidates, key=lambda d: d.effective_at)


def verify_federated_card(
    vc: VerifiableCredential,
    history: list[DidDocumentVersion],
    policy: RotationPolicy,
    now: datetime,
) -> DidDocumentVersion:
    """Bind the credential to exactly one DID document version.

    Returns the document version under which the credential is authoritative.
    Raises TrustAnchorRotationError if the binding is ambiguous or violated.
    """
    if vc.expiration is not None and vc.expiration <= now:
        raise TrustAnchorRotationError(
            f"credential from {vc.issuer_did} expired at {vc.expiration.isoformat()}"
        )

    lifetime = (vc.expiration - vc.issuance) if vc.expiration else None
    unbounded = lifetime is None
    exceeds_rotation_window = unbounded or lifetime > policy.max_interval

    if exceeds_rotation_window:
        # Strict policy: must bind to issuance-time document, not current state.
        doc = _resolve_at(vc.issuer_did, vc.issuance, history)
        if vc.signing_key_id not in doc.verification_methods:
            raise TrustAnchorRotationError(
                f"signing key {vc.signing_key_id} was not authoritative for "
                f"{vc.issuer_did} at issuance {vc.issuance.isoformat()}"
            )
        if doc.controllers != _resolve_at(vc.issuer_did, vc.issuance, history).controllers:
            # Defensive: controller set must be singular at issuance.
            raise TrustAnchorRotationError(
                f"ambiguous controller set for {vc.issuer_did} at issuance"
            )
        return doc

    # Lenient policy: credential lifetime is bounded within the rotation window,
    # so current-state resolution is sound.
    current = _resolve_at(vc.issuer_did, now, history)
    if vc.signing_key_id not in current.verification_methods:
        raise TrustAnchorRotationError(
            f"signing key {vc.signing_key_id} not present in current document for "
            f"{vc.issuer_did}; rotation occurred inside credential lifetime"
        )
    return current


def audit_binding(vc: VerifiableCredential, history: list[DidDocumentVersion], policy: RotationPolicy, now: datetime) -> str:
    """Record both the version used and the version that strict policy would have required."""
    used = verify_federated_card(vc, history, policy, now)
    strict = _resolve_at(vc.issuer_did, vc.issuance, history)
    digest = hashlib.sha256(
        f"{used.effective_at.isoformat()}|{strict.effective_at.isoformat()}|{vc.claims_hash}".encode()
    ).hexdigest()
    if used.effective_at != strict.effective_at:
        return f"LENIENT_BINDING used={used.effective_at.isoformat()} strict={strict.effective_at.isoformat()} digest={digest}"
    return f"STRICT_BINDING at={used.effective_at.isoformat()} digest={digest}"
