import requests
import hashlib
import sys
import stdiomask

def request_api_data(query_char):
    url = 'https://api.pwnedpasswords.com/range/' + query_char
    response = requests.get(url)
    if response.status_code != 200:
        raise RuntimeError(f'Error fetching: {response.status_code}, check the API and try again')
    return response

def get_password_leaks_count(raw_hash_string, hash_to_check):
    hashes = (line.split(':') for line in raw_hash_string.text.splitlines())
    for h, count in hashes:
        if h == hash_to_check:
            return count
    return 0

def pwned_api_check(password):
    sha1password = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
    first5_chars, tail = sha1password[:5], sha1password[5:]
    response = request_api_data(first5_chars)    
    return get_password_leaks_count(response, tail)

def main(password):
    count = pwned_api_check(password)
    if count:
        print(f'{password} was found {count} times...you should probably change your password!')
    else:
        print(f'{password} was NOT found. Carry on!')
    return 'done!'

if __name__ == '__main__':
    password_to_check = stdiomask.getpass(prompt='Please enter your password to check: ', mask='*')
    sys.exit(main(password_to_check))