"""Simple script to promote a user to super admin using raw SQL."""
import asyncio
import sys
from sqlalchemy import text
from app.core.database import engine


async def make_super_admin(email: str):
    """Promote a user to super admin by email."""
    async with engine.begin() as conn:
        # Check if user exists
        result = await conn.execute(
            text("SELECT email, is_super_admin FROM users WHERE email = :email"),
            {"email": email}
        )
        row = result.fetchone()

        if not row:
            print(f"[X] User not found: {email}")
            return False

        if row[1]:  # is_super_admin
            print(f"[OK] {email} is already a super admin")
            return True

        # Promote to super admin
        await conn.execute(
            text("UPDATE users SET is_super_admin = TRUE WHERE email = :email"),
            {"email": email}
        )
        print(f"[OK] {email} promoted to super admin")
        return True


async def list_users():
    """List all users and their admin status."""
    async with engine.connect() as conn:
        result = await conn.execute(
            text("SELECT email, is_super_admin, is_active FROM users ORDER BY created_at")
        )
        rows = result.fetchall()

        if not rows:
            print("No users found")
            return

        print("\nCurrent users:")
        print("-" * 70)
        for email, is_super_admin, is_active in rows:
            admin_badge = "[SUPER ADMIN]" if is_super_admin else ""
            active_badge = "[ACTIVE]" if is_active else "[INACTIVE]"
            print(f"{active_badge:12} {email:40} {admin_badge}")
        print("-" * 60)


async def main():
    if len(sys.argv) < 2:
        print("Usage:")
        print("  python make_superadmin_simple.py list              - List all users")
        print("  python make_superadmin_simple.py <email>           - Promote user to super admin")
        sys.exit(1)

    command = sys.argv[1]

    if command == "list":
        await list_users()
    else:
        email = command
        await make_super_admin(email)


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