"""Create first admin (superuser). Usage:
    cd /path/to/kelly && python -m scripts.create_superuser --email admin@example.com --password 'SecurePass123'
"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

# Allow running without installing package
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from sqlalchemy.orm import Session

from app.database import SessionLocal, init_db
from app.models import User, UserRole
from app.security import hash_password
from app.services.admin_profile_service import ensure_admin_profile


def main() -> None:
    parser = argparse.ArgumentParser(description="Create admin superuser")
    parser.add_argument("--email", required=True)
    parser.add_argument("--password", required=True)
    parser.add_argument("--full-name", default="Administrator")
    parser.add_argument(
        "--reset-password",
        action="store_true",
        help="If the admin already exists, update their password instead of failing.",
    )
    args = parser.parse_args()

    init_db()
    db: Session = SessionLocal()
    try:
        existing = db.query(User).filter(User.email == args.email).first()
        if existing:
            if not args.reset_password:
                print("User with this email already exists. Use --reset-password to update the password.")
                sys.exit(1)
            existing.hashed_password = hash_password(args.password)
            existing.role = UserRole.admin
            existing.is_active = True
            if args.full_name:
                existing.full_name = args.full_name
            db.commit()
            db.refresh(existing)
            ensure_admin_profile(db, existing)
            print(f"Admin password updated: {args.email}")
            return
        u = User(
            email=args.email,
            hashed_password=hash_password(args.password),
            full_name=args.full_name,
            role=UserRole.admin,
            is_active=True,
        )
        db.add(u)
        db.flush()
        ensure_admin_profile(db, u)
        db.commit()
        print(f"Admin created: {args.email}")
    finally:
        db.close()


if __name__ == "__main__":
    main()
