"""Creates a Super Admin (platform_admins) account — the first one on a new
server, since nothing else makes one:

    python scripts/create_platform_admin.py --name "Ops Admin" --email ops@example.com

It asks for the password (or pass --password). Run inside the API
container in production:

    docker compose -f docker-compose.prod.yml exec backend \
        python scripts/create_platform_admin.py --name "Ops Admin" --email ops@example.com
"""

import argparse
import asyncio
import getpass
import sys
from pathlib import Path

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

from sqlalchemy import select  # noqa: E402

from app.core.auth import hash_password  # noqa: E402
from app.core.database import AsyncSessionLocal  # noqa: E402
from app.models.platform_admin import PlatformAdmin  # noqa: E402


async def main(name: str, email: str, password: str) -> None:
    async with AsyncSessionLocal() as db:
        if await db.scalar(select(PlatformAdmin.id).where(PlatformAdmin.email == email)):
            sys.exit(f"A Super Admin with email {email} already exists.")
        admin = PlatformAdmin(name=name, email=email, password_hash=hash_password(password))
        db.add(admin)
        await db.commit()
        print(f"Created Super Admin {email} ({admin.id}).")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--name", required=True)
    parser.add_argument("--email", required=True)
    parser.add_argument("--password", default=None, help="omit to be asked for it")
    args = parser.parse_args()
    password = args.password
    if password is None:
        password = getpass.getpass("Password: ")
        if password != getpass.getpass("Again: "):
            sys.exit("The passwords don't match.")
    if len(password) < 12:
        sys.exit("Use at least 12 characters.")
    asyncio.run(main(args.name, args.email.strip(), password))
