"""Create initial admin user interactively."""

import os
import sys

# Allow imports from the backend package when running this script directly.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from getpass import getpass

from app.core.security import hash_password
from app.database import SessionLocal
from app.models.user import User


def main() -> None:
    db = SessionLocal()
    try:
        username = input("Admin username: ").strip()
        if not username:
            print("Username cannot be empty.")
            sys.exit(1)

        email = input("Admin email: ").strip()
        if not email:
            print("Email cannot be empty.")
            sys.exit(1)

        password = getpass("Admin password: ")
        confirm = getpass("Confirm password: ")

        if password != confirm:
            print("Passwords don't match!")
            sys.exit(1)

        if len(password) < 8:
            print("Password must be at least 8 characters.")
            sys.exit(1)

        existing = (
            db.query(User)
            .filter((User.email == email) | (User.username == username))
            .first()
        )
        if existing:
            print(f"User already exists: {existing.username} ({existing.email})")
            sys.exit(1)

        user = User(
            username=username,
            email=email,
            password_hash=hash_password(password),
            role="admin",
        )
        db.add(user)
        db.commit()
        print(f"Admin user created: {username} ({email})")
    finally:
        db.close()


if __name__ == "__main__":
    main()
