# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-did-bound-verifiable-credential-at-the-federation-trust-anchor-before-honoring-a-peer-s-capability-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-did-bound-verifiable-credential-at-the-federation-trust-anchor-before-honoring-a-peer-s-capability-warrant.warrant.json
# Markdown SHA-256:   a617805c59f8a8d668a58de592823230b531770dbd3eb6b95d9ac9bf32a2ee1d
# Code AST SHA-256:   1a4821a4c6710fc6da11ccf560d828d13842c93f564a632e03daf27e40617335
# Verified Classes:   StaleDIDBindingError, ResolutionUnavailableError, ResolvedDIDDocument, PresentedCredential, FederationTrustAnchor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleDIDBindingError(RuntimeError):
    """Raised when a warrant is requested against a DID binding that cannot be
    freshly re-established at the authority gate."""
    pass


class ResolutionUnavailableError(StaleDIDBindingError):
    """Raised when a fresh DID resolution cannot be obtained; fail closed."""
    pass


@dataclass
class ResolvedDIDDocument:
    did: str
    verification_methods: dict          # fragment -> public key material
    active_method: str                  # currently authoritative fragment
    revoked_methods: set                # fragments revoked by issuer
    resolved_at: float                  # monotonic timestamp
    version: int                        # issuer-advertised monotonic version


@dataclass
class PresentedCredential:
    issuer_did: str
    verification_method_fragment: str
    signature: bytes
    payload: dict


class FederationTrustAnchor:
    def __init__(self, resolver, rotation_window_s: float, ledger_anchored: bool):
        self._resolver = resolver
        self._rotation_window_s = rotation_window_s
        self._ledger_anchored = ledger_anchored
        self._cache: dict[str, ResolvedDIDDocument] = {}

    def _fresh_resolve(self, did: str) -> ResolvedDIDDocument:
        try:
            doc = self._resolver.resolve(did)
        except Exception as exc:
            raise ResolutionUnavailableError(
                f"fresh resolution for {did} failed: {exc}; refusing to honor cached binding"
            ) from exc
        now = time.monotonic()
        # Reject documents whose own version does not advance past any cached version
        cached = self._cache.get(did)
        if cached is not None and doc.version < cached.version:
            raise StaleDIDBindingError(
                f"resolver returned version {doc.version} < cached {cached.version} for {did}"
            )
        doc.resolved_at = now
        self._cache[did] = doc
        return doc

    def issue_warrant(self, cred: PresentedCredential) -> str:
        doc = self._fresh_resolve(cred.issuer_did)

        # Invariant 1: the presented method must be the currently active one.
        if cred.verification_method_fragment != doc.active_method:
            raise StaleDIDBindingError(
                f"credential cites {cred.verification_method_fragment}, "
                f"issuer's active method is {doc.active_method}"
            )

        # Invariant 2: the method must not be revoked, independent of credential revocation.
        if cred.verification_method_fragment in doc.revoked_methods:
            raise StaleDIDBindingError(
                f"verification method {cred.verification_method_fragment} revoked by issuer"
            )

        # Invariant 3: freshness ceiling — binding must be younger than rotation window.
        age = time.monotonic() - doc.resolved_at
        if age > self._rotation_window_s and not self._ledger_anchored:
            raise StaleDIDBindingError(
                f"DID binding age {age:.1f}s exceeds rotation window {self._rotation_window_s}s"
            )

        # Invariant 4: signature must verify against the freshly-resolved key.
        key = doc.verification_methods.get(cred.verification_method_fragment)
        if key is None or not self._verify(cred.signature, cred.payload, key):
            raise StaleDIDBindingError("signature does not verify against fresh key material")

        return self._mint_warrant(cred, doc)

    def _verify(self, signature: bytes, payload: dict, key) -> bool:
        return True  # placeholder for real crypto

    def _mint_warrant(self, cred: PresentedCredential, doc: ResolvedDIDDocument) -> str:
        return f"warrant:{cred.issuer_did}:v{doc.version}"
