import os
import sys
from getpass import getpass
from db import get_connection

sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from services.auth_service import hash_password


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

    if not username:
        print("Username is required")
        return

    if not password:
        print("Password is required")
        return

    password_hash = hash_password(password)

    conn = get_connection()
    try:
        with conn:
            with conn.cursor() as cur:
                cur.execute(
                    """
                    INSERT INTO admin_users (username, password_hash, is_active)
                    VALUES (%s, %s, TRUE)
                    ON CONFLICT (username) DO NOTHING
                    RETURNING id;
                    """,
                    (username, password_hash),
                )
                row = cur.fetchone()

                if row:
                    print(f"User created: {username} (id={row[0]})")
                else:
                    print(f"User '{username}' already exists")
    finally:
        conn.close()


if __name__ == "__main__":
    main()