"""
Create Super Admin Script
Run this script to create the platform super admin account.

Usage:
    python create_super_admin.py --email admin@platform.com --username superadmin --password YourSecurePass123
"""
import asyncio
import argparse
import uuid
import os
import sys
from datetime import datetime
from pathlib import Path

from dotenv import load_dotenv
from motor.motor_asyncio import AsyncIOMotorClient
from passlib.context import CryptContext

ROOT_DIR = Path(__file__).parent
load_dotenv(ROOT_DIR / '.env')

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


async def create_super_admin(email: str, username: str, password: str):
    mongo_url = os.environ.get("MONGO_URL", "mongodb://localhost:27017")
    db_name = os.environ.get("DB_NAME", "nms_esafe")

    client = AsyncIOMotorClient(mongo_url)
    db = client[db_name]

    existing = await db.users.find_one({"email": email})
    if existing:
        if existing.get("role") == "super_admin":
            print(f"Super admin with email '{email}' already exists.")
            client.close()
            return
        else:
            await db.users.update_one(
                {"email": email},
                {"$set": {"role": "super_admin", "is_active": True, "updated_at": datetime.utcnow()}}
            )
            print(f"Existing user '{email}' promoted to super_admin.")
            client.close()
            return

    super_admin = {
        "id": str(uuid.uuid4()),
        "email": email,
        "username": username,
        "hashed_password": pwd_context.hash(password),
        "role": "super_admin",
        "is_active": True,
        "status": "approved",
        "created_at": datetime.utcnow(),
        "organization_id": None,
        "is_super_admin": True,
    }

    await db.users.insert_one(super_admin)
    print(f"\nSuper Admin created successfully!")
    print(f"  Email:    {email}")
    print(f"  Username: {username}")
    print(f"  Role:     super_admin")
    print(f"  ID:       {super_admin['id']}")
    print(f"\nYou can now login with these credentials on web or mobile app.")

    client.close()


def main():
    parser = argparse.ArgumentParser(description="Create NMS-ESAFE Super Admin")
    parser.add_argument("--email", required=True, help="Super admin email")
    parser.add_argument("--username", required=True, help="Super admin username")
    parser.add_argument("--password", required=True, help="Super admin password")

    args = parser.parse_args()

    if len(args.password) < 8:
        print("Error: Password must be at least 8 characters long.")
        sys.exit(1)

    asyncio.run(create_super_admin(args.email, args.username, args.password))


if __name__ == "__main__":
    main()
