import hmac
import os
import secrets
from django.contrib.auth import login
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import transaction
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.accounts_rbac.constants import ALL_PERMISSIONS, ROLE_PRESETS
from apps.accounts_rbac.models import CompanyMembership, 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.models import InstallationSession
from apps.system_admin.services.install_and_updates import (
    EnvironmentCheckerService,
    InstallationWizardService,
    ReleaseAndUpdateService,
)


def _is_bootstrap_open() -> bool:
    if User.objects.filter(is_superuser=True, is_active=True).exists():
        return False
    sess = InstallationSession.objects.order_by("-created_at").first()
    if sess and sess.status == InstallationSession.Status.LOCKED:
        return False
    return True


def _verify_setup_token(provided: str) -> bool:
    expected = os.getenv("BOOTSTRAP_SETUP_TOKEN", "").strip()
    if not expected:
        return False
    return hmac.compare_digest(str(provided or "").strip(), expected)


class BootstrapStatusView(APIView):
    """Pre-auth probe reporting whether fresh database requires initial Super Admin setup."""

    permission_classes = [permissions.AllowAny]
    authentication_classes = []

    def get(self, request):
        has_superadmin = User.objects.filter(is_superuser=True, is_active=True).exists()
        sess = InstallationSession.objects.order_by("-created_at").first()
        setup_locked = bool(has_superadmin or (sess and sess.status == InstallationSession.Status.LOCKED))
        payload = {
            "initialized": has_superadmin,
            "setup_locked": setup_locked,
            "bootstrap_allowed": not setup_locked,
            "token_configured": bool(os.getenv("BOOTSTRAP_SETUP_TOKEN", "").strip()),
        }
        if not setup_locked:
            payload["environment"] = EnvironmentCheckerService.run_checks()
        return Response(payload)


class BootstrapSuperAdminView(APIView):
    """
    One-time cryptographic bootstrap endpoint to create the initial Super Admin
    and initialize mandatory TOTP MFA on a completely empty MySQL installation.
    Automatically & permanently disables once a Super Admin exists.
    """

    permission_classes = [permissions.AllowAny]
    authentication_classes = []
    throttle_scope = "login"

    @transaction.atomic
    def post(self, request):
        if not _is_bootstrap_open():
            return Response(
                {"detail": "Bootstrap endpoint is permanently locked after initial Super Admin creation."},
                status=status.HTTP_403_FORBIDDEN,
            )

        token = request.data.get("setup_token") or request.headers.get("X-Bootstrap-Token", "")
        if not _verify_setup_token(token):
            return Response(
                {"detail": "Invalid or missing BOOTSTRAP_SETUP_TOKEN."},
                status=status.HTTP_403_FORBIDDEN,
            )

        username = str(request.data.get("username") or "").strip()
        email = str(request.data.get("email") or "").strip().lower()
        full_name = str(request.data.get("full_name") or "").strip()
        password = str(request.data.get("password") or "")
        if not username or not email or not password:
            return Response({"detail": "username, email, and strong password are required."}, status=status.HTTP_400_BAD_REQUEST)

        # Reject weak or default usernames
        if username.lower() in {"admin", "root", "test", "demo", "user"}:
            return Response(
                {"detail": "Default usernames ('admin', 'root', 'test', 'demo') are prohibited in production."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:
            temp_user = User(username=username, email=email, full_name=full_name)
            validate_password(password, user=temp_user)
        except DjangoValidationError as exc:
            return Response({"detail": exc.messages}, status=status.HTTP_400_BAD_REQUEST)

        user = User.objects.create_superuser(
            username=username,
            email=email,
            password=password,
            full_name=full_name or username,
            preferred_language="en",
            timezone_name=os.getenv("APP_TIME_ZONE", "Asia/Kathmandu"),
            date_preference="BS",
        )

        # Ensure system roles, navigation, BS calendar dataset, and baseline release record
        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_bundle = MfaEnrollmentService.initiate_setup(user=user)
        sess = InstallationWizardService.get_or_create_session()
        sess.current_step = max(sess.current_step, 9)
        sess.save(update_fields=["current_step"])

        record_audit_event(
            actor=user,
            action="BOOTSTRAP_SUPERADMIN_CREATED",
            entity_type="User",
            entity_id=str(user.id),
            new_state={"username": user.username, "email": user.email, "mfa_initiated": True},
        )

        login(request, user, backend="django.contrib.auth.backends.ModelBackend")
        return Response(
            {
                "created": True,
                "user": {
                    "id": str(user.id),
                    "username": user.username,
                    "email": user.email,
                    "full_name": user.full_name,
                },
                "mfa_setup": {
                    "credential_id": mfa_bundle.get("credential_id"),
                    "secret": mfa_bundle["manual_secret"],
                    "otpauth_uri": mfa_bundle["provisioning_uri"],
                    "recovery_codes": mfa_bundle["recovery_codes"],
                },
            },
            status=status.HTTP_201_CREATED,
        )


class BootstrapConfirmMfaView(APIView):
    """Confirms the initial Super Admin TOTP MFA enrollment during the setup wizard."""

    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        if not request.user.is_superuser:
            return Response({"detail": "Super Admin required."}, status=status.HTTP_403_FORBIDDEN)
        code = str(request.data.get("totp_code") or "").strip()
        try:
            ok = MfaEnrollmentService.confirm_enrollment(user=request.user, code=code)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
        if not ok:
            return Response({"detail": "Invalid 6-digit TOTP authenticator code."}, status=status.HTTP_400_BAD_REQUEST)
        return Response({"mfa_verified": True})
