"""
Seed script to create the first superadmin user in Firestore.

Usage:
    python seed_admin.py
    python seed_admin.py --email admin@bellsystems.com --password secret --name "Admin"
"""
import argparse
import sys
from getpass import getpass

from shared.firebase import init_firebase, get_db
from auth.utils import hash_password


def seed_superadmin(email: str, password: str, name: str):
    init_firebase()
    db = get_db()
    if not db:
        print("ERROR: Firebase initialization failed.")
        sys.exit(1)

    existing = (
        db.collection("admin_users")
        .where("email", "==", email)
        .limit(1)
        .get()
    )
    if existing:
        print(f"User with email '{email}' already exists. Aborting.")
        sys.exit(1)

    user_data = {
        "email": email,
        "hashed_password": hash_password(password),
        "name": name,
        "role": "sysadmin",
        "is_active": True,
    }

    doc_ref = db.collection("admin_users").add(user_data)
    print(f"SysAdmin created successfully!")
    print(f"  Email:  {email}")
    print(f"  Name:   {name}")
    print(f"  Role:   sysadmin")
    print(f"  Doc ID: {doc_ref[1].id}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Seed a superadmin user")
    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: ")

    seed_superadmin(email, password, name)
