#!/usr/bin/env python3
"""
Script to create an admin user for testing the VFX Project Management System.
"""

from sqlalchemy.orm import Session
from database import SessionLocal, engine
from models.user import User, UserRole
from utils.auth import get_password_hash


def create_admin_user():
    """Create an admin user for testing."""
    
    # Create database session
    db: Session = SessionLocal()
    
    try:
        # Check if admin user already exists
        existing_admin = db.query(User).filter(
            User.email == "admin@vfx.com"
        ).first()
        
        if existing_admin:
            print("Admin user already exists!")
            print(f"Email: {existing_admin.email}")
            print(f"Role: {existing_admin.role}")
            print(f"Approved: {existing_admin.is_approved}")
            return existing_admin
        
        # Create admin user
        password = "admin123"
        if len(password.encode('utf-8')) > 72:
            password = password[:72]
            
        admin_user = User(
            email="admin@vfx.com",
            password_hash=get_password_hash(password),
            first_name="Admin",
            last_name="User",
            role=UserRole.COORDINATOR,  # Default functional role
            is_admin=True,  # Grant admin permission
            is_approved=True  # Admin is automatically approved
        )
        
        db.add(admin_user)
        db.commit()
        db.refresh(admin_user)
        
        print("✅ Admin user created successfully!")
        print(f"Email: {admin_user.email}")
        print(f"Password: admin123")
        print(f"Role: {admin_user.role}")
        print(f"ID: {admin_user.id}")
        
        return admin_user
        
    except Exception as e:
        print(f"❌ Error creating admin user: {e}")
        db.rollback()
        return None
    finally:
        db.close()


def create_test_users():
    """Create additional test users for different roles."""
    
    db: Session = SessionLocal()
    
    test_users = [
        {
            "email": "director@vfx.com",
            "password": "director123",
            "first_name": "John",
            "last_name": "Director",
            "role": UserRole.DIRECTOR,
            "is_approved": True
        },
        {
            "email": "coordinator@vfx.com", 
            "password": "coord123",
            "first_name": "Jane",
            "last_name": "Coordinator",
            "role": UserRole.COORDINATOR,
            "is_approved": True
        },
        {
            "email": "artist@vfx.com",
            "password": "artist123", 
            "first_name": "Bob",
            "last_name": "Artist",
            "role": UserRole.ARTIST,
            "is_approved": True
        }
    ]
    
    try:
        created_users = []
        
        for user_data in test_users:
            # Check if user already exists
            existing_user = db.query(User).filter(
                User.email == user_data["email"]
            ).first()
            
            if existing_user:
                print(f"User {user_data['email']} already exists, skipping...")
                continue
            
            # Create user
            password = user_data["password"]
            if len(password.encode('utf-8')) > 72:
                password = password[:72]
                
            user = User(
                email=user_data["email"],
                password_hash=get_password_hash(password),
                first_name=user_data["first_name"],
                last_name=user_data["last_name"],
                role=user_data["role"],
                is_approved=user_data["is_approved"]
            )
            
            db.add(user)
            created_users.append(user_data)
        
        db.commit()
        
        if created_users:
            print(f"\n✅ Created {len(created_users)} test users:")
            for user_data in created_users:
                print(f"  - {user_data['email']} (password: {user_data['password']}) - {user_data['role']}")
        else:
            print("\n📝 All test users already exist")
            
    except Exception as e:
        print(f"❌ Error creating test users: {e}")
        db.rollback()
    finally:
        db.close()


if __name__ == "__main__":
    print("Creating admin user for VFX Project Management System...")
    
    # Create admin user
    admin = create_admin_user()
    
    if admin:
        print("\n" + "="*50)
        print("ADMIN LOGIN CREDENTIALS")
        print("="*50)
        print("Email: admin@vfx.com")
        print("Password: admin123")
        print("="*50)
        
        # Ask if user wants to create additional test users
        create_more = input("\nCreate additional test users? (y/n): ").lower().strip()
        if create_more in ['y', 'yes']:
            create_test_users()
            
        print("\n🚀 You can now login to the system!")
        print("📖 API Documentation: http://127.0.0.1:8000/docs")
        print("🔍 Health Check: http://127.0.0.1:8000/health")