import getpass

from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = "Idempotent first-run setup: roles, reference data, optional UAT sample data and first Super Admin."

    def add_arguments(self, parser):
        parser.add_argument("--with-demo-data", action="store_true")
        parser.add_argument("--skip-admin", action="store_true")

    def handle(self, *args, **options):
        call_command("bootstrap_roles")
        call_command("seed_reference_data")
        if options["with_demo_data"]:
            call_command("seed_uat_demo_data")

        User = get_user_model()
        if not options["skip_admin"] and not User.objects.filter(is_superuser=True).exists():
            self.stdout.write("\nCreate the first Super Admin (password input is hidden).")
            username = (input("Username [admin]: ").strip() or "admin")
            email = input("Email (optional): ").strip()
            if User.objects.filter(username=username).exists():
                raise CommandError("That username already exists. Choose another username or use --skip-admin.")
            while True:
                password1 = getpass.getpass("Password: ")
                password2 = getpass.getpass("Confirm password: ")
                if password1 != password2:
                    self.stdout.write(self.style.ERROR("Passwords do not match."))
                    continue
                if len(password1) < 10:
                    self.stdout.write(self.style.ERROR("Use at least 10 characters."))
                    continue
                break
            user = User.objects.create_superuser(username=username, email=email, password=password1)
            user.display_name = "Super Admin"
            user.force_password_change = False
            user.save(update_fields=["display_name", "force_password_change", "updated_at"])
            self.stdout.write(self.style.SUCCESS(f"Super Admin created: {username}"))
        elif User.objects.filter(is_superuser=True).exists():
            self.stdout.write(self.style.SUCCESS("Super Admin already exists."))

        call_command("verify_runtime")
        self.stdout.write(self.style.SUCCESS("First-run setup completed."))
