import asyncio
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import modules  # noqa
from sqlalchemy import select
from core.security import hash_password
from infrastructure.database.session import get_db_session
from modules.identity.models import User


async def create_superadmin(email: str, password: str, full_name: str = "Super Admin"):
    print(f"👑 Creating Superadmin: {email}...")
    async with get_db_session() as session:
        stmt = select(User).where(User.email == email.lower().strip())
        res = await session.execute(stmt)
        user = res.scalar_one_or_none()

        if user:
            print(f"  * User {email} already exists. Promoting to superuser...")
            user.is_superuser = True
            user.password_hash = hash_password(password)
            user.status = "active"
        else:
            user = User(
                email=email.lower().strip(),
                password_hash=hash_password(password),
                full_name=full_name,
                status="active",
                is_superuser=True,
            )
            session.add(user)

        await session.commit()
    print("✅ Superadmin created/updated successfully.")


if __name__ == "__main__":
    email = sys.argv[1] if len(sys.argv) > 1 else "superadmin@saas.local"
    password = sys.argv[2] if len(sys.argv) > 2 else "AdminSuperSecure2026!"
    asyncio.run(create_superadmin(email, password))
