from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from apps.accounts_rbac.constants import ROLE_PRESETS
from apps.accounts_rbac.models import Role, User
from apps.accounts_rbac.services.mfa_and_security import MfaEnrollmentService
from apps.audit.services import record_audit_event
from apps.localization.services import CalendarDataVersionService
from apps.navigation.registry import ensure_default_navigation
from apps.system_admin.services.install_and_updates import ReleaseAndUpdateService


class Command(BaseCommand):
    help = "Securely create the initial Super Admin account and initialize baseline platform metadata (zero demo data)."

    def add_arguments(self, parser):
        parser.add_argument("--username", required=True)
        parser.add_argument("--email", required=True)
        parser.add_argument("--full-name", default="")
        parser.add_argument("--password", required=True)

    @transaction.atomic
    def handle(self, *args, **options):
        username = options["username"].strip()
        email = options["email"].strip().lower()
        full_name = options["full_name"].strip() or username
        password = options["password"]

        if username.lower() in {"admin", "root", "test", "demo"}:
            raise CommandError("Default usernames ('admin', 'root', 'test', 'demo') are prohibited.")
        if User.objects.filter(username=username).exists():
            raise CommandError(f"User '{username}' already exists.")

        try:
            validate_password(password, user=User(username=username, email=email, full_name=full_name))
        except ValidationError as exc:
            raise CommandError("; ".join(exc.messages)) from exc

        user = User.objects.create_superuser(
            username=username,
            email=email,
            password=password,
            full_name=full_name,
            preferred_language="en",
            timezone_name="Asia/Kathmandu",
            date_preference="BS",
        )
        for rcode, spec in ROLE_PRESETS.items():
            Role.objects.get_or_create(
                code=rcode,
                defaults={
                    "name": spec["name"],
                    "description": spec["description"],
                    "permissions": spec["permissions"],
                    "is_system": True,
                    "default_dashboard_template": spec["template"],
                },
            )
        ensure_default_navigation()
        CalendarDataVersionService.ensure_default_dataset_seeded(actor=user)
        ReleaseAndUpdateService.ensure_baseline_release()
        mfa = MfaEnrollmentService.initiate_setup(user=user)
        record_audit_event(
            actor=user,
            action="CLI_SUPERADMIN_BOOTSTRAPPED",
            entity_type="User",
            entity_id=str(user.id),
            new_state={"username": username, "email": email},
        )
        self.stdout.write(
            self.style.SUCCESS(
                f"Super Admin '{username}' created. Mandatory MFA initiated (TOTP URI available on first login / Install Wizard)."
            )
        )
        self.stdout.write(f"MFA_PROVISIONING_URI={mfa['provisioning_uri']}")
