"""
Script to create an admin user account.
Usage: python backend/scripts/create_admin.py
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from db.db import users_db
from models.user import User
from werkzeug.security import generate_password_hash
from tinydb import Query
import uuid

def create_admin_user(email: str, password: str, first_name: str, last_name: str):
    """Create an admin user account."""
    
    # Check if user already exists
    Query_ = Query()
    existing_user = users_db.get(Query_.email == email)
    
    if existing_user:
        print(f"Error: User with email {email} already exists")
        return False
    
    admin = User(
        id=str(uuid.uuid4()),
        email=email,
        first_name=first_name,
        last_name=last_name,
        password=generate_password_hash(password),
        verified=True,
        role='admin'
    )
    
    users_db.insert(admin.to_dict())
    print(f"✓ Admin user created successfully!")
    print(f"  Email: {email}")
    print(f"  Name: {first_name} {last_name}")
    print(f"  Role: admin")
    return True

if __name__ == '__main__':
    print("=== Create Admin User ===\n")
    
    email = input("Email: ").strip()
    password = input("Password: ").strip()
    first_name = input("First name: ").strip()
    last_name = input("Last name: ").strip()
    
    if not all([email, password, first_name, last_name]):
        print("Error: All fields are required")
        sys.exit(1)
    
    if len(password) < 8:
        print("Error: Password must be at least 8 characters")
        sys.exit(1)
    
    confirm = input(f"\nCreate admin user '{email}'? (yes/no): ").strip().lower()
    
    if confirm == 'yes':
        create_admin_user(email, password, first_name, last_name)
    else:
        print("Cancelled")
