import os
import sqlite3
import bcrypt

# Configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATABASE_PATH = os.path.join(BASE_DIR, 'theialogin.db')

def get_db():
    conn = sqlite3.connect(DATABASE_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def register_user(username, password):
    db = get_db()
    cursor = db.cursor()

    # Hash the password
    password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

    try:
        cursor.execute('INSERT INTO users (username, password_hash) VALUES (?, ?)', (username, password_hash))
        db.commit()
        print(f"User {username} registered successfully.")
    except sqlite3.IntegrityError:
        print(f"Username {username} is already taken.")
    except sqlite3.Error as e:
        print(f"An error occurred: {e}")
    finally:
        db.close()

if __name__ == '__main__':
    # Take user input for registration
    username = input("Enter username: ")
    password = input("Enter password: ")
    
    register_user(username, password)
