import requests
import hashlib
import sys


def request_api_data(query_password):
    url = 'https://api.pwnedpasswords.com/range/' + query_password
    res = requests.get(url)
    if res.status_code != 200:
        raise RuntimeError(f"Error fetching {res.status_code}")
    return res


def get_password_leaks_count(hashes, hash_to_check):
    #hashes is the response received from the api, hash_to_check is the tail of the hash of our password which we want to check.
    #hashes.text returns the entire text of the response.
    #It consists of all the hashes in the api's database which have the same first 5 characters as we have provided.
    #In each line of the text, the hashes are followed by a ':' and then the number of times the corresponding password has been hacked.
    hashes = (line.split(':') for line in hashes.text.split('\n'))
    for h, count in hashes:
        #print(h, count)
        if h == hash_to_check:
            return count
    return 0


def pwned_api_check(password):
    #Running the password through the SHA1 Hash function to generate a secure hexadecimal representation of our password.
    #Password needs to be encoded with 'utf-8' encoding.
    #hexdigest ensures the string is composed of hexadecimal characters.
    #upper converts the entire string to upper case to match the string generated by the api's hash function.
    SHA1_password = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()

    #Now we pass the first 5 characters of the string to the api to check.
    first5_char , remaining_char = SHA1_password[:5], SHA1_password[5:]
    response = request_api_data(first5_char)
    return get_password_leaks_count(response, remaining_char)


def main(args):
    for password in args:
        count = pwned_api_check(password)
        if count == 0:
            print("Your password has not been hacked. It is safe and secure to use.")
        else:
            print(f"Your password has been heacked {int(count)} times. It is recommended that you change your password.")

main(sys.argv[1:])

