import hashlib
import requests


def check_password(password):
    """Check a given password against known data breaches

    Note:
        This method uses the `Have I Been Pwned <https://haveibeenpwned.com/>`_ Passwords API. The unhashed password nor its full `SHA-1 <https://en.wikipedia.org/wiki/SHA-1>`_ hash never leave the device.

    Args:
        password (str): The password to check

    Returns:
        int: The number of times the password has been found
    """

    sha1 = hashlib.sha1(password.encode("utf-8")).hexdigest()

    response = requests.get(f"https://api.pwnedpasswords.com/range/{sha1[:5]}")

    hash_suffix_list = [x.split(":") for x in response.text.splitlines(False)]

    try:
        count = [
            count for suffix, count in hash_suffix_list if sha1.endswith(suffix.lower())
        ][0]
    except IndexError:
        return 0

    return int(count)