# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-agent-credential-whose-did-document-has-been-rotated-between-warrant-issuance-and-warrant-presen.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-agent-credential-whose-did-document-has-been-rotated-between-warrant-issuance-and-warrant-presen.warrant.json
# Markdown SHA-256:   95259cfaf942e6ced9134194bf4c1bce8f38d9cec0419ca52dd7a101877ed761
# Code AST SHA-256:   ce0d7a5f58247409c9da1b5b8e7abd7c710bdfa174685f668574a4f66e1ab737
# Verified Classes:   FederationTrustError, DidDocumentVersion, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class FederationTrustError(RuntimeError):
    """Raised when a federated warrant cannot be safely admitted under DID rotation."""


@dataclass
class DidDocumentVersion:
    version_id: int
    controller: str
    verification_keys: frozenset[str]   # key ids, e.g. "#key-1"
    revoked_keys: frozenset[str] = field(default_factory=frozenset)


@dataclass
class Warrant:
    issuer: str
    subject: str
    signing_key_id: str
    did_version_at_issuance: int
    issued_at: int
    expires_at: int


def admit_federated_warrant(
    warrant: Warrant,
    did_chain: list[DidDocumentVersion],   # ordered, oldest first, from trusted resolver
    now: int,
) -> dict:
    if now >= warrant.expires_at:
        raise FederationTrustError(
            f"warrant {warrant.subject} expired at {warrant.expires_at}, now={now}"
        )
    if not did_chain:
        raise FederationTrustError("resolver returned empty DID history; cannot verify rotation")

    # Locate the document version that was current at issuance.
    issued_doc = next(
        (d for d in did_chain if d.version_id == warrant.did_version_at_issuance), None
    )
    if issued_doc is None:
        raise FederationTrustError(
            f"no DID document version {warrant.did_version_at_issuance} in chain; "
            f"cannot prove signing key was authorized at issuance"
        )

    # (a) signing key must have been authorized at issuance
    if warrant.signing_key_id not in issued_doc.verification_keys:
        raise FederationTrustError(
            f"signing key {warrant.signing_key_id} was not authorized by DID version "
            f"{issued_doc.version_id} at issuance"
        )

    current = did_chain[-1]

    # (b) signing key must not be revoked as of the latest known version
    if warrant.signing_key_id in current.revoked_keys:
        raise FederationTrustError(
            f"signing key {warrant.signing_key_id} is revoked in current DID version "
            f"{current.version_id}; likely compromise-response rotation"
        )

    # (c) controller must be stable, or the change must be countersigned (not modeled here)
    if current.controller != issued_doc.controller:
        raise FederationTrustError(
            f"DID controller changed from {issued_doc.controller!r} to "
            f"{current.controller!r} between issuance and presentation; "
            f"presenter is a different principal"
        )

    # Clean path: signing key still current.
    if warrant.signing_key_id in current.verification_keys:
        return {"decision": "admit", "bind_key": warrant.signing_key_id}

    # Attenuated path: signing key rotated out benignly; bind session to current key.
    if not current.verification_keys:
        raise FederationTrustError(
            f"DID version {current.version_id} has no verification keys; cannot bind session"
        )
    present_key = sorted(current.verification_keys)[0]
    return {
        "decision": "admit-attenuated",
        "bind_key": present_key,
        "historical_key": warrant.signing_key_id,
        "session_ttl": min(300, warrant.expires_at - now),
    }


def _demo() -> None:
    chain = [
        DidDocumentVersion(1, "org-b", frozenset({"#key-1"})),
        DidDocumentVersion(2, "org-b", frozenset({"#key-2"}), frozenset({"#key-1"})),
    ]
    benign = Warrant("issuer", "agent-7", "#key-1", 1, 0, 10_000)
    # key-1 revoked -> must raise, not silently admit via stale pin
    admit_federated_warrant(benign, chain, now=100)


if __name__ == "__main__":
    _demo()
