import json
import sys
from getpass import getpass
from hashlib import sha256

PWDB_PATH = 'pwdb.json'

def get_credentials():
    username = input('Enter your username: ')
    hashed_password = pwhash(getpass('Enter your password: '))
    return (username, hashed_password)

def authenticate(username, hashed_password, pwdb):
    return hashed_password == pwdb[username]

def add_user(username, pwdb):
    pwdb[username] = pwhash(getpass(f'Enter password for {username}: '))
    return pwdb

def read_pwdb(PWDB_PATH):
    try:
        pwdb_file = open(PWDB_PATH, 'rt')
        pwdb = json.load(pwdb_file)
    except Exception:
        pwdb = {}
    return pwdb

def write_pwdb(pwdb, PWDB_PATH):
    pwdb_file = open(PWDB_PATH, 'wt')
    json.dump(pwdb, pwdb_file)


def pwhash(pwd):
    encoded_pwd = pwd.encode("utf-8")
    m = sha256()
    m.update(encoded_pwd)
    return m.hexdigest()

if __name__ == "__main__":
    PWDB_PATH = 'pwdb.json'
    pwdb = read_pwdb(PWDB_PATH)

    if len(sys.argv) > 1:
        pwdb = add_user(sys.argv[1], pwdb)
        write_pwdb(pwdb, PWDB_PATH)
    else:
        username, password = get_credentials()
        if username not in pwdb:
            print('Wrong username!')
        else:
            if authenticate(username, password, pwdb):
                print('Successfully authenticated!')
            else:
                print('Wrong password!')

