# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-did-anchored-verifiable-credential-handshake-when-the-trust-anchor-s-key-rotation-outpaces-the-credential.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-did-anchored-verifiable-credential-handshake-when-the-trust-anchor-s-key-rotation-outpaces-the-credential.warrant.json
# Markdown SHA-256:   7e35e11235ff969c2a55b8d6c5e5f9683150e6d4b19ca84b0d4256439d1db0ce
# Code AST SHA-256:   287c3164c1ffc30ccef5a4d1321973b39c24fa7f95529021f68fcc047717ab5a
# Verified Classes:   AnchorRotationAmbiguity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AnchorRotationAmbiguity(RuntimeError):
    """Raised when a VC's signing key is absent from the DID head document
    and the instance cannot determine whether the key was rotated (valid,
    proof predates retirement) or never existed / was retired before signing
    (invalid, replay or skew). Callers MUST NOT map this to a generic
    'untrusted peer' memory write."""
    pass


def verify_federated_vc(proof_created: float, verification_method: str,
                        head_doc: dict, history: list[dict],
                        deactivated_keys: set[str]) -> str:
    key_id = verification_method.split("#", 1)[-1]

    if key_id in deactivated_keys:
        # Explicit revocation: hard reject, distinct from ambiguity.
        raise AnchorRotationAmbiguity(
            f"key {key_id} is deactivated; credential is revoked, not rotated"
        )

    head_keys = {k["id"] for k in head_doc.get("verificationMethod", [])}
    if key_id in head_keys:
        return "valid-current"

    # Head-miss: must resolve against a historical version whose validity
    # interval contains the proof timestamp.
    for version in history:
        keys = {k["id"] for k in version.get("verificationMethod", [])}
        if key_id not in keys:
            continue
        if version["validFrom"] <= proof_created < version["validUntil"]:
            return "valid-rotated"
        # Key present but proof timestamp outside its validity window:
        # signed with a retired key -> replay or clock skew.
        raise AnchorRotationAmbiguity(
            f"key {key_id} present in version but proof_created "
            f"{proof_created} outside [{version['validFrom']}, "
            f"{version['validUntil']}); possible replay/skew"
        )

    # Key absent from head and from all history: unresolvable, NOT invalid.
    raise AnchorRotationAmbiguity(
        f"key {key_id} absent from head and history; anchor unresolvable, "
        f"do not poison peer-trust memory"
    )
