import json
import sys
from getpass import getpass

PWDB_PATH = 'pwdb.json'

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

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

def add_user(username, pwdb):
    pwdb[username] = 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)


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!')

