"""
Seed script to create the first sysadmin user directly in Postgres.
Use this after Phase 3 cutover — do not use seed_admin.py (Firestore) anymore.

Usage:
    python seed_admin_postgres.py
    python seed_admin_postgres.py --email admin@bellsystems.com --password secret --name "Admin"
"""
import argparse
import asyncio
import sys
import uuid
from datetime import datetime, timezone
from getpass import getpass

from sqlalchemy import select

from database.postgres import AsyncSessionLocal
from staff.orm import Staff
from auth.utils import hash_password


async def seed_superadmin(email: str, password: str, name: str) -> None:
    async with AsyncSessionLocal() as db:
        existing = await db.execute(select(Staff).where(Staff.email == email).limit(1))
        if existing.scalar_one_or_none() is not None:
            print(f"User with email '{email}' already exists. Aborting.")
            sys.exit(1)

        now = datetime.now(timezone.utc)
        uid = str(uuid.uuid4())
        staff = Staff(
            id=uid,
            firestore_id=None,
            email=email,
            name=name,
            role="sysadmin",
            hashed_password=hash_password(password),
            is_active=True,
            permissions=None,
            ui_prefs={},
            created_at=now,
            updated_at=now,
        )
        db.add(staff)
        await db.commit()

    print("SysAdmin created successfully!")
    print(f"  Email: {email}")
    print(f"  Name:  {name}")
    print(f"  Role:  sysadmin")
    print(f"  ID:    {uid}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Seed a sysadmin user in Postgres")
    parser.add_argument("--email", default=None)
    parser.add_argument("--password", default=None)
    parser.add_argument("--name", default=None)
    args = parser.parse_args()

    email    = args.email    or input("Email: ")
    name     = args.name     or input("Name: ")
    password = args.password or getpass("Password: ")

    asyncio.run(seed_superadmin(email, password, name))
