import bcrypt
import os

DB_FILE = "db.txt"


def ensure_db():
    if not os.path.exists(DB_FILE):
        open(DB_FILE, "w").close()


def username_exists(username):
    with open(DB_FILE, "r") as f:
        for line in f:
            if not line.strip():
                continue
            user, _ = line.strip().split("|", 1)
            if user == username:
                return True
    return False


def register():
    username = input("Enter Username: ").strip()

    if username_exists(username):
        print("Username already exists.")
        return

    password = input("Enter Password: ")

    hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()

    with open(DB_FILE, "a") as f:
        f.write(f"{username}|{hashed}\n")

    print("Registration Successful.")


def login():
    username = input("Username: ").strip()
    password = input("Password: ")

    with open(DB_FILE, "r") as f:
        for line in f:
            if not line.strip():
                continue

            user, stored_hash = line.strip().split("|", 1)

            if user == username:
                if bcrypt.checkpw(password.encode(), stored_hash.encode()):
                    print("Login Successful.")
                else:
                    print("Wrong Password.")
                return

    print("User not found.")


def change_password():
    username = input("Username: ").strip()
    old_password = input("Current Password: ")

    lines = []
    changed = False

    with open(DB_FILE, "r") as f:
        for line in f:
            if not line.strip():
                continue

            user, stored_hash = line.strip().split("|", 1)

            if user == username and bcrypt.checkpw(old_password.encode(), stored_hash.encode()):
                new_password = input("New Password: ")
                new_hash = bcrypt.hashpw(
                    new_password.encode(),
                    bcrypt.gensalt()
                ).decode()

                lines.append(f"{user}|{new_hash}\n")
                changed = True
            else:
                lines.append(line)

    with open(DB_FILE, "w") as f:
        f.writelines(lines)

    if changed:
        print("Password Changed.")
    else:
        print("Invalid Username or Password.")


ensure_db()

while True:
    print("\n====== LOGIN SYSTEM ======")
    print("1. Register")
    print("2. Login")
    print("3. Change Password")
    print("4. Exit")

    choice = input("Choose: ")

    if choice == "1":
        register()

    elif choice == "2":
        login()

    elif choice == "3":
        change_password()

    elif choice == "4":
        print("Goodbye!")
        break

    else:
        print("Invalid Choice.")