#!/usr/bin/env python3

import getpass
import hashlib
import sys
import urllib.request


def pwck(password):
    if password is None:
        if sys.stdin.isatty():
            password = getpass.getpass()
        else:
            password = sys.stdin.read().rstrip()

    sha1 = hashlib.sha1(password.encode("utf8")).hexdigest().upper()
    prefix = sha1[0:5]
    suffix = sha1[5:]

    res = urllib.request.urlopen(f"https://api.pwnedpasswords.com/range/{prefix}")
    for line in res.read().splitlines():
        hash, num = line.decode("ascii").split(":")
        if hash == suffix:
            return int(num)

    return 0


def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("-q", "--quiet", action="store_true", help="suppress output")
    parser.add_argument("password", nargs="?")

    args = parser.parse_args()

    matches = pwck(args.password)
    if not args.quiet:
        if matches > 0:
            print(
                f"The password you entered was found {matches} times in known data "
                "breaches."
            )
        else:
            print("The password you entered was not found in any known data breaches.")

    return 0 if matches == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
