"""Define some utilities to work with SimpliSafe's authentication mechanism."""
import base64
import hashlib
import os
import re


def get_auth0_code_challenge(code_verifier: str) -> str:
    """Get an Auth0 code challenge from a code verifier.

    :param code_verifier: A code challenge generated by
        :meth:`simplipy.util.auth.get_auth0_code_verifier`
    :type code_verifier: ``str``
    :rtype: ``str``
    """
    verifier = hashlib.sha256(code_verifier.encode("utf-8")).digest()
    challenge = base64.urlsafe_b64encode(verifier).decode("utf-8")
    return challenge.replace("=", "")


def get_auth0_code_verifier() -> str:
    """Get an Auth0 code verifier.

    :rtype: ``str``
    """
    verifier = base64.urlsafe_b64encode(os.urandom(40)).decode("utf-8")
    return re.sub("[^a-zA-Z0-9]+", "", verifier)
