"""Script to create an admin user in the database."""

import sys
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from passlib.context import CryptContext
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from admin.backend.app.config import Settings
from admin.backend.app.models import Base, AdminUser

# Password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def create_admin_user(email: str, password: str, role: str = "sysop"):
    """Create an admin user with the given credentials."""
    settings = Settings()
    
    # Create engine and session
    engine = create_engine(settings.database_url)
    Base.metadata.create_all(bind=engine)
    
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    session = SessionLocal()
    
    try:
        # Check if user already exists
        existing = session.query(AdminUser).filter(AdminUser.email == email).first()
        if existing:
            print(f"❌ User {email} already exists!")
            print(f"   Current role: {existing.role}")
            
            # Update password if needed
            update = input("Do you want to update the password? (y/n): ")
            if update.lower() == 'y':
                existing.hashed_password = pwd_context.hash(password)
                session.commit()
                print(f"✅ Password updated for {email}")
            return
        
        # Create new admin user
        hashed_password = pwd_context.hash(password)
        admin = AdminUser(
            email=email,
            hashed_password=hashed_password,
            role=role
        )
        
        session.add(admin)
        session.commit()
        
        print(f"✅ Admin user created successfully!")
        print(f"   Email: {email}")
        print(f"   Role: {role}")
        print(f"   Status: Active")
        
    except Exception as e:
        session.rollback()
        print(f"❌ Error creating admin user: {e}")
        raise
    finally:
        session.close()


if __name__ == "__main__":
    # Admin credentials
    EMAIL = "bruno@taaazzz-prog.fr"
    PASSWORD = "@51008473@ZoE@"
    ROLE = "sysop"  # sysop, admin, manager, viewer
    
    print("=" * 60)
    print("🛡️  Web Sentinel - Admin User Creation")
    print("=" * 60)
    print(f"Creating admin user: {EMAIL}")
    print(f"Role: {ROLE}")
    print()
    
    create_admin_user(EMAIL, PASSWORD, ROLE)
    
    print()
    print("=" * 60)
    print("🎉 You can now login to the admin panel!")
    print(f"   URL: http://localhost:5173")
    print(f"   Email: {EMAIL}")
    print(f"   Password: {PASSWORD}")
    print("=" * 60)
