from typing import Tuple
from typing import Union
import base64


def is_fernet_key(key: str) -> Tuple[bool, Union[str, None]]:
    """Check if the Fernet key is valid.
    :param key: Key to check.
    :return: Validity, and an error message if not valid.
    """

    key_bytes = bytes(key, "utf-8")

    try:
        decoded_key = base64.urlsafe_b64decode(key_bytes)
    except:
        message = f"Key {key} could not be urlsafe b64decoded."
        return False, message

    key_length = len(decoded_key)
    if key_length != 32:
        message = f"Decoded Fernet key should be length 32, but is length {key_length}."
        return False, message

    message = None
    return True, message