#!/usr/bin/env python3
"""Check and create admin user"""

import asyncio
import sys
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select
import bcrypt
from datetime import datetime, timezone

sys.path.append('/media/pts/Website/PromptTech_Solution_Site/backend')
from models import User, UserRole
from database import DATABASE_URL

async def check_and_create_admin():
    engine = create_async_engine(DATABASE_URL, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as session:
        # Check for existing admin
        result = await session.execute(select(User))
        users = result.scalars().all()
        
        print(f"\n📊 Current users in database:")
        for user in users:
            print(f"  - {user.email} (Role: {user.role.value})")
        
        # Check if admin@prompttech.com exists
        result = await session.execute(
            select(User).where(User.email == "admin@prompttech.com")
        )
        admin = result.scalar_one_or_none()
        
        if admin:
            print(f"\n✅ Admin user already exists: admin@prompttech.com")
            print(f"   If you can't login, the password should be: admin123")
        else:
            print(f"\n⚠️  Admin user not found. Creating new admin...")
            
            # Create admin user
            email = "admin@prompttech.com"
            password = "admin123"
            name = "Admin User"
            
            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
            
            admin_user = User(
                email=email,
                name=name,
                password=hashed_password,
                role=UserRole.ADMIN,
                created_at=datetime.now(timezone.utc)
            )
            
            session.add(admin_user)
            await session.commit()
            
            print(f"\n✅ Admin user created!")
            print(f"   Email: {email}")
            print(f"   Password: {password}")

if __name__ == "__main__":
    asyncio.run(check_and_create_admin())
