"""Script to promote a user to super admin."""
import asyncio
import sys
from sqlalchemy import select
from app.core.database import async_session_maker

# Import models to ensure they're registered
import app.models.user
import app.models.tree
import app.models.account
from app.models.user import User


async def make_super_admin(email: str):
    """Promote a user to super admin by email."""
    async with async_session_maker() as db:
        result = await db.execute(select(User).where(User.email == email))
        user = result.scalar_one_or_none()

        if not user:
            print(f"❌ User not found: {email}")
            return False

        if user.is_super_admin:
            print(f"✅ {email} is already a super admin")
            return True

        user.is_super_admin = True
        await db.commit()
        print(f"✅ {email} promoted to super admin")
        return True


async def list_users():
    """List all users and their admin status."""
    async with async_session_maker() as db:
        result = await db.execute(
            select(User.email, User.is_super_admin, User.is_active)
            .order_by(User.created_at)
        )
        users = result.all()

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

        print("\n📋 Current users:")
        print("-" * 60)
        for email, is_super_admin, is_active in users:
            admin_badge = "🔑 SUPER ADMIN" if is_super_admin else ""
            active_badge = "✅" if is_active else "❌ INACTIVE"
            print(f"{active_badge} {email:40} {admin_badge}")
        print("-" * 60)


async def main():
    if len(sys.argv) < 2:
        print("Usage:")
        print("  python make_superadmin.py list              - List all users")
        print("  python make_superadmin.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())
