import uuid
from decimal import Decimal
from pathlib import Path

from django.db import transaction
from django.db.models import F, Q
from django.http import FileResponse, HttpResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework import permissions, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.accounts_rbac.constants import Permissions, ROLE_PRESETS
from apps.accounts_rbac.models import CompanyMembership, Device, Role, RoleChangeHistory, User
from apps.accounts_rbac.permissions import HasCompanyPermission
from apps.audit.models import AuditEvent
from apps.audit.services import record_audit_event
from apps.system_admin.models import (
    ApiIntegrationKey,
    BackupArtifact,
    BackupSchedule,
    ConfigurationHistory,
    CriticalOperationRequest,
    DisasterRecoveryPlan,
    InstallationSession,
    RestoreJob,
    SecurityLoginEvent,
    SoftwareDeploymentJob,
    SoftwareRelease,
    SystemMaintenanceState,
)
from apps.system_admin.serializers import (
    AdminAuditEventSerializer,
    ApiIntegrationKeySerializer,
    BackupArtifactSerializer,
    BackupScheduleSerializer,
    ConfigurationHistorySerializer,
    CriticalOperationRequestSerializer,
    DisasterRecoveryPlanSerializer,
    InstallationSessionSerializer,
    PlatformUserSerializer,
    RestoreJobSerializer,
    SecurityLoginEventSerializer,
    SoftwareDeploymentJobSerializer,
    SoftwareReleaseSerializer,
    SystemMaintenanceStateSerializer,
)
from apps.system_admin.services import (
    AdminReportingService,
    ApiIntegrationService,
    BackupService,
    CompanyProvisioningService,
    EnvironmentCheckerService,
    HealthCheckService,
    InstallationWizardService,
    ReleaseAndUpdateService,
    RestoreService,
    SystemConfigurationService,
)
from apps.tenancy.models import Branch, Company, FiscalPeriod, FiscalYear, TaxConfig
from apps.tenancy.serializers import BranchSerializer, CompanySerializer, FiscalPeriodSerializer, FiscalYearSerializer, TaxConfigSerializer


class AdminPermissionMixin:
    permission_classes = [HasCompanyPermission]


class AdminOverviewView(AdminPermissionMixin, APIView):
    required_permission = [Permissions.SYSTEM_VIEW, Permissions.COMPANY_MANAGE, Permissions.BACKUP_MANAGE]

    def get(self, request):
        ReleaseAndUpdateService.ensure_baseline_release()
        health = HealthCheckService.get_system_health()
        recent_backups = BackupArtifactSerializer(BackupArtifact.objects.all()[:5], many=True).data
        recent_deployments = SoftwareDeploymentJobSerializer(
            SoftwareDeploymentJob.objects.select_related("to_version").all()[:5], many=True
        ).data
        recent_logins = SecurityLoginEventSerializer(SecurityLoginEvent.objects.all()[:8], many=True).data
        pending_critical = CriticalOperationRequestSerializer(
            CriticalOperationRequest.objects.filter(status=CriticalOperationRequest.Status.PENDING)[:5],
            many=True,
        ).data
        return Response(
            {
                "health": health,
                "recent_backups": recent_backups,
                "recent_deployments": recent_deployments,
                "recent_security_events": recent_logins,
                "pending_critical_approvals": pending_critical,
                "companies_count": Company.objects.filter(is_active=True).count(),
            }
        )


class AdminHealthView(AdminPermissionMixin, APIView):
    required_permission = [Permissions.SYSTEM_VIEW, Permissions.COMPANY_MANAGE]

    def get(self, request):
        return Response(HealthCheckService.get_system_health())


class BackupArtifactViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "list": [Permissions.BACKUP_MANAGE, Permissions.SYSTEM_VIEW],
        "create": Permissions.BACKUP_MANAGE,
        "verify": Permissions.BACKUP_MANAGE,
        "download": Permissions.BACKUP_MANAGE,
        "destroy": Permissions.BACKUP_MANAGE,
    }

    def list(self, request):
        qs = BackupArtifact.objects.all()
        scope = request.query_params.get("scope")
        if scope:
            qs = qs.filter(scope=scope)
        status_f = request.query_params.get("status")
        if status_f:
            qs = qs.filter(status=status_f)
        return Response(BackupArtifactSerializer(qs[:100], many=True).data)

    def create(self, request):
        scope = request.data.get("scope", BackupArtifact.Scope.DATABASE)
        encrypt = bool(request.data.get("encrypt", False))
        notes = request.data.get("notes", "")
        verify_now = bool(request.data.get("verify_now", True))
        artifact = BackupService.create_backup(
            scope=scope,
            trigger_type=BackupArtifact.TriggerType.MANUAL,
            company=getattr(request, "company", None),
            actor=request.user,
            notes=notes,
            encrypt=encrypt,
            verify_now=verify_now,
        )
        return Response(BackupArtifactSerializer(artifact).data, status=status.HTTP_201_CREATED)

    @action(detail=True, methods=["post"])
    def verify(self, request, pk=None):
        artifact = get_object_or_404(BackupArtifact, id=pk)
        report = BackupService.verify_backup(artifact, actor=request.user)
        return Response({"backup": BackupArtifactSerializer(artifact).data, "report": report})

    @action(detail=True, methods=["get"])
    def download(self, request, pk=None):
        artifact = get_object_or_404(BackupArtifact, id=pk)
        path = Path(artifact.file_path) if artifact.file_path else None
        if not path or not path.exists():
            return Response({"detail": "Backup file not found on disk."}, status=status.HTTP_404_NOT_FOUND)
        record_audit_event(
            company=getattr(request, "company", None),
            actor=request.user,
            action="BACKUP_DOWNLOADED",
            entity_type="BackupArtifact",
            entity_id=str(artifact.id),
            new_state={"backup_code": artifact.backup_code},
        )
        return FileResponse(path.open("rb"), as_attachment=True, filename=path.name)

    def destroy(self, request, pk=None):
        artifact = get_object_or_404(BackupArtifact, id=pk)
        valid_count = BackupArtifact.objects.filter(
            status__in=[BackupArtifact.Status.COMPLETED, BackupArtifact.Status.VERIFIED]
        ).count()
        if artifact.status in (BackupArtifact.Status.COMPLETED, BackupArtifact.Status.VERIFIED) and valid_count <= 1:
            return Response(
                {"detail": "Cannot delete the last remaining valid backup artifact."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        if artifact.file_path:
            Path(artifact.file_path).unlink(missing_ok=True)
        artifact.status = BackupArtifact.Status.DELETED
        artifact.save(update_fields=["status"])
        record_audit_event(
            actor=request.user,
            action="BACKUP_DELETED",
            entity_type="BackupArtifact",
            entity_id=str(artifact.id),
            new_state={"backup_code": artifact.backup_code},
        )
        return Response(status=status.HTTP_204_NO_CONTENT)


class BackupScheduleViewSet(AdminPermissionMixin, viewsets.ModelViewSet):
    serializer_class = BackupScheduleSerializer
    queryset = BackupSchedule.objects.all()
    action_permissions = {
        "list": Permissions.BACKUP_MANAGE,
        "retrieve": Permissions.BACKUP_MANAGE,
        "create": Permissions.BACKUP_MANAGE,
        "update": Permissions.BACKUP_MANAGE,
        "partial_update": Permissions.BACKUP_MANAGE,
        "destroy": Permissions.BACKUP_MANAGE,
        "run_now": Permissions.BACKUP_MANAGE,
    }

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=["post"], url_path="run-now")
    def run_now(self, request, pk=None):
        sched = self.get_object()
        artifact = BackupService.run_schedule(sched, actor=request.user)
        return Response(BackupArtifactSerializer(artifact).data, status=status.HTTP_201_CREATED)


class RestoreViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "list": Permissions.BACKUP_MANAGE,
        "test_recovery": Permissions.RESTORE_EXECUTE,
        "execute": Permissions.RESTORE_EXECUTE,
    }

    def list(self, request):
        return Response(RestoreJobSerializer(RestoreJob.objects.all()[:50], many=True).data)

    @action(detail=False, methods=["post"], url_path="test-recovery")
    def test_recovery(self, request):
        backup = get_object_or_404(BackupArtifact, id=request.data.get("backup_id"))
        job = RestoreService.run_isolated_recovery_test(backup=backup, actor=request.user)
        return Response(RestoreJobSerializer(job).data, status=status.HTTP_201_CREATED)

    @action(detail=False, methods=["post"], url_path="execute")
    def execute(self, request):
        backup = get_object_or_404(BackupArtifact, id=request.data.get("backup_id"))
        critical_req = None
        if request.data.get("critical_request_id"):
            critical_req = get_object_or_404(CriticalOperationRequest, id=request.data["critical_request_id"])
        try:
            job = RestoreService.initiate_live_restore(
                backup=backup,
                restore_mode=request.data.get("restore_mode", RestoreJob.RestoreMode.FULL_SYSTEM),
                confirmation_phrase=request.data.get("confirmation_phrase", ""),
                actor=request.user,
                reason=request.data.get("reason", ""),
                critical_request=critical_req,
            )
            return Response(RestoreJobSerializer(job).data, status=status.HTTP_201_CREATED)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class DisasterRecoveryPlanView(AdminPermissionMixin, APIView):
    required_permission = Permissions.BACKUP_MANAGE

    def _get_plan(self) -> DisasterRecoveryPlan:
        plan = DisasterRecoveryPlan.objects.order_by("-updated_at").first()
        if not plan:
            plan = DisasterRecoveryPlan.objects.create(
                checklist_steps=[
                    {"step": 1, "title": "Enable Maintenance Mode & Freeze Writes", "done": False},
                    {"step": 2, "title": "Verify Latest Offsite Backup SHA-256", "done": False},
                    {"step": 3, "title": "Run Isolated Sandbox Recovery Drill", "done": False},
                    {"step": 4, "title": "Execute Database Restore & Verify GL TB Parity", "done": False},
                    {"step": 5, "title": "Disable Maintenance Mode & Notify Operations", "done": False},
                ]
            )
        return plan

    def get(self, request):
        return Response(DisasterRecoveryPlanSerializer(self._get_plan()).data)

    def put(self, request):
        plan = self._get_plan()
        ser = DisasterRecoveryPlanSerializer(plan, data=request.data, partial=True)
        ser.is_valid(raise_exception=True)
        ser.save()
        record_audit_event(
            actor=request.user,
            action="DR_PLAN_UPDATED",
            entity_type="DisasterRecoveryPlan",
            entity_id=str(plan.id),
            new_state=ser.data,
        )
        return Response(ser.data)


class InstallWizardView(AdminPermissionMixin, APIView):
    action_permissions = {
        "get": [Permissions.INSTALL_MANAGE, Permissions.SYSTEM_VIEW],
        "post": Permissions.INSTALL_MANAGE,
    }

    def get(self, request):
        sess = InstallationWizardService.get_or_create_session()
        return Response(
            {
                "session": InstallationSessionSerializer(sess).data,
                "steps": InstallationWizardService.STEP_TITLES,
                "environment": EnvironmentCheckerService.run_checks(),
            }
        )

    def post(self, request):
        step = int(request.data.get("step", 1))
        payload = request.data.get("payload") or {}
        finalize = bool(request.data.get("finalize", False))
        try:
            sess = InstallationWizardService.advance_step(
                step=step, payload=payload, actor=request.user, finalize=finalize
            )
            return Response(InstallationSessionSerializer(sess).data)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class EnvironmentCheckView(AdminPermissionMixin, APIView):
    required_permission = [Permissions.SYSTEM_VIEW, Permissions.INSTALL_MANAGE]

    def get(self, request):
        return Response(EnvironmentCheckerService.run_checks())


class SoftwareReleaseViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "list": [Permissions.SYSTEM_VIEW, Permissions.UPDATE_MANAGE],
        "stage": Permissions.UPDATE_MANAGE,
        "preflight": Permissions.UPDATE_MANAGE,
        "upgrade": Permissions.UPDATE_MANAGE,
        "rollback": Permissions.UPDATE_MANAGE,
        "migrations_status": [Permissions.SYSTEM_VIEW, Permissions.UPDATE_MANAGE],
        "deployments": [Permissions.SYSTEM_VIEW, Permissions.UPDATE_MANAGE],
    }

    def list(self, request):
        ReleaseAndUpdateService.ensure_baseline_release()
        return Response(
            {
                "releases": SoftwareReleaseSerializer(SoftwareRelease.objects.all(), many=True).data,
                "deployments": SoftwareDeploymentJobSerializer(
                    SoftwareDeploymentJob.objects.select_related("to_version").all()[:30], many=True
                ).data,
                "migrations": ReleaseAndUpdateService.get_migration_status(),
            }
        )

    @action(detail=False, methods=["post"])
    def stage(self, request):
        ver = (request.data.get("version") or "").strip()
        if not ver:
            return Response({"detail": "version is required."}, status=status.HTTP_400_BAD_REQUEST)
        rel = SoftwareRelease.objects.create(
            version=ver,
            build_number=request.data.get("build_number", f"{timezone.now():%Y.%m.%d}"),
            channel=request.data.get("channel", SoftwareRelease.Channel.STABLE),
            release_notes=request.data.get("release_notes", ""),
            changelog_items=request.data.get("changelog_items", []),
            manifest_sha256=request.data.get("manifest_sha256", ""),
            signature_status=request.data.get("signature_status", SoftwareRelease.SignatureStatus.UNSIGNED),
            min_compatible_version=request.data.get("min_compatible_version", "1.0.0"),
        )
        return Response(SoftwareReleaseSerializer(rel).data, status=status.HTTP_201_CREATED)

    @action(detail=True, methods=["post"])
    def preflight(self, request, pk=None):
        rel = get_object_or_404(SoftwareRelease, id=pk)
        return Response(ReleaseAndUpdateService.validate_release_preflight(rel))

    @action(detail=True, methods=["post"])
    def upgrade(self, request, pk=None):
        rel = get_object_or_404(SoftwareRelease, id=pk)
        try:
            job = ReleaseAndUpdateService.execute_upgrade(release=rel, actor=request.user)
            return Response(SoftwareDeploymentJobSerializer(job).data)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=["post"])
    def rollback(self, request, pk=None):
        rel = get_object_or_404(SoftwareRelease, id=pk)
        try:
            job = ReleaseAndUpdateService.rollback_to_release(
                target_release=rel, actor=request.user, reason=request.data.get("reason", "")
            )
            return Response(SoftwareDeploymentJobSerializer(job).data)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=["get"], url_path="migrations")
    def migrations_status(self, request):
        return Response(ReleaseAndUpdateService.get_migration_status())


class MaintenanceModeView(AdminPermissionMixin, APIView):
    action_permissions = {
        "get": [Permissions.SYSTEM_VIEW, Permissions.SYSTEM_MANAGE],
        "post": Permissions.SYSTEM_MANAGE,
    }

    def _state(self) -> SystemMaintenanceState:
        st, _ = SystemMaintenanceState.objects.get_or_create(
            id=uuid.UUID("00000000-0000-0000-0000-000000000001")
        )
        return st

    def get(self, request):
        return Response(SystemMaintenanceStateSerializer(self._state()).data)

    def post(self, request):
        if not request.user.is_superuser:
            raise PermissionDenied("Only Super Admins may toggle system-wide Maintenance Mode.")
        st = self._state()
        st.is_maintenance_mode = bool(request.data.get("is_maintenance_mode", False))
        st.reason = request.data.get("reason", st.reason)
        st.banner_message = request.data.get("banner_message", st.banner_message)
        if "allowed_ips" in request.data:
            st.allowed_ips = request.data["allowed_ips"] or []
        st.enabled_by = request.user
        st.enabled_at = timezone.now() if st.is_maintenance_mode else st.enabled_at
        st.save()
        record_audit_event(
            actor=request.user,
            action="MAINTENANCE_MODE_CHANGED",
            entity_type="SystemMaintenanceState",
            entity_id=str(st.id),
            new_state={"is_maintenance_mode": st.is_maintenance_mode, "reason": st.reason},
        )
        return Response(SystemMaintenanceStateSerializer(st).data)


class AdminCompanyViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "list": Permissions.COMPANY_MANAGE,
        "create": Permissions.COMPANY_MANAGE,
        "partial_update": Permissions.COMPANY_MANAGE,
        "deactivate": Permissions.COMPANY_MANAGE,
        "create_branch": Permissions.COMPANY_MANAGE,
        "create_fiscal_year": Permissions.PERIOD_MANAGE,
        "rollforward_fiscal_year": Permissions.PERIOD_MANAGE,
        "lock_period": Permissions.PERIOD_MANAGE,
        "open_period": Permissions.PERIOD_MANAGE,
        "create_tax_config": Permissions.COMPANY_MANAGE,
    }

    def list(self, request):
        qs = Company.objects.prefetch_related("branches", "fiscal_years__periods", "tax_configs").order_by("code")
        if not request.user.is_superuser:
            ids = CompanyMembership.objects.filter(user=request.user, is_active=True).values_list("company_id", flat=True)
            qs = qs.filter(id__in=ids)
        return Response(CompanySerializer(qs, many=True).data)

    def create(self, request):
        try:
            company = CompanyProvisioningService.provision_company(
                code=request.data["code"],
                name=request.data["name"],
                registration_no=request.data.get("registration_no", ""),
                pan_vat_no=request.data.get("pan_vat_no", ""),
                base_currency=request.data.get("base_currency", "NPR"),
                calendar_preference=request.data.get("calendar_preference", Company.CalendarPref.BS),
                default_vat_rate=Decimal(str(request.data.get("default_vat_rate", "13.00"))),
                branch_code=request.data.get("branch_code", "HO-01"),
                branch_name=request.data.get("branch_name", "Head Office"),
                fiscal_year_name=request.data.get("fiscal_year_name", "2083/84"),
                bs_start_year=int(request.data.get("bs_start_year", 2083)),
                seed_default_coa=bool(request.data.get("seed_default_coa", True)),
                actor=request.user,
            )
            return Response(CompanySerializer(company).data, status=status.HTTP_201_CREATED)
        except Exception as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)

    def partial_update(self, request, pk=None):
        company = get_object_or_404(Company, id=pk)
        for fld in ("name", "registration_no", "pan_vat_no", "base_currency", "calendar_preference", "default_vat_rate", "multi_currency_enabled", "nfrs_enabled"):
            if fld in request.data:
                setattr(company, fld, request.data[fld])
        company.full_clean()
        company.save()
        record_audit_event(company=company, actor=request.user, action="COMPANY_UPDATED", entity_type="Company", entity_id=str(company.id))
        return Response(CompanySerializer(company).data)

    @action(detail=True, methods=["post"])
    def deactivate(self, request, pk=None):
        company = get_object_or_404(Company, id=pk)
        if Company.objects.filter(is_active=True).count() <= 1 and company.is_active:
            return Response({"detail": "Cannot deactivate the only active company."}, status=status.HTTP_400_BAD_REQUEST)
        company.is_active = bool(request.data.get("is_active", False))
        company.save(update_fields=["is_active"])
        record_audit_event(company=company, actor=request.user, action="COMPANY_STATUS_CHANGED", entity_type="Company", entity_id=str(company.id), new_state={"is_active": company.is_active})
        return Response(CompanySerializer(company).data)

    @action(detail=True, methods=["post"], url_path="branches")
    def create_branch(self, request, pk=None):
        company = get_object_or_404(Company, id=pk)
        b = Branch.objects.create(
            company=company,
            code=request.data["code"].upper().strip(),
            name=request.data["name"].strip(),
            address=request.data.get("address", ""),
            is_head_office=bool(request.data.get("is_head_office", False)),
        )
        return Response(BranchSerializer(b).data, status=status.HTTP_201_CREATED)

    @action(detail=True, methods=["post"], url_path="fiscal-years")
    def create_fiscal_year(self, request, pk=None):
        company = get_object_or_404(Company, id=pk)
        bs_year = int(request.data.get("bs_start_year", 2084))
        from apps.localization.bs_calendar import bs_to_ad

        fy = FiscalYear.objects.create(
            company=company,
            name=request.data["name"],
            start_date=request.data.get("start_date") or bs_to_ad(bs_year, 4, 1),
            end_date=request.data.get("end_date") or bs_to_ad(bs_year + 1, 3, 31),
            is_current=bool(request.data.get("is_current", False)),
        )
        fy.generate_nepal_periods(bs_year)
        return Response(FiscalYearSerializer(fy).data, status=status.HTTP_201_CREATED)

    @action(detail=False, methods=["post"], url_path="rollforward-fy")
    def rollforward_fiscal_year(self, request):
        fy = get_object_or_404(FiscalYear, id=request.data.get("fiscal_year_id"))
        try:
            res = CompanyProvisioningService.rollforward_fiscal_year(
                fiscal_year=fy,
                next_name=request.data["next_name"],
                next_bs_start_year=int(request.data["next_bs_start_year"]),
                actor=request.user,
            )
            return Response(res)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=["post"], url_path="period-status")
    def lock_period(self, request):
        period = get_object_or_404(FiscalPeriod, id=request.data.get("period_id"))
        new_status = request.data.get("status", FiscalPeriod.Status.LOCKED)
        if period.status == FiscalPeriod.Status.CLOSED:
            return Response({"detail": "Closed period cannot be unlocked directly."}, status=status.HTTP_400_BAD_REQUEST)
        period.status = new_status
        period.save(update_fields=["status"])
        return Response(FiscalPeriodSerializer(period).data)

    @action(detail=True, methods=["post"], url_path="tax-configs")
    def create_tax_config(self, request, pk=None):
        company = get_object_or_404(Company, id=pk)
        tc = TaxConfig.objects.create(
            company=company,
            code=request.data["code"].upper().strip(),
            name=request.data["name"].strip(),
            tax_type=request.data["tax_type"],
            rate=Decimal(str(request.data["rate"])),
        )
        return Response(TaxConfigSerializer(tc).data, status=status.HTTP_201_CREATED)


class AdminUserGovernanceViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "list": [Permissions.ACCESS_VIEW, Permissions.SUPER_ADMIN_MANAGE],
        "create": Permissions.ACCESS_MANAGE,
        "partial_update": Permissions.ACCESS_MANAGE,
        "reset_password": Permissions.ACCESS_MANAGE,
        "force_logout": Permissions.DEVICE_MANAGE,
        "assign_company": Permissions.ACCESS_MANAGE,
    }

    def list(self, request):
        tier = (request.query_params.get("tier") or "ALL").upper()
        qs = User.objects.prefetch_related("memberships__company", "memberships__role").order_by("username")
        if not request.user.is_superuser:
            qs = qs.filter(memberships__company=request.company).distinct()
        data = PlatformUserSerializer(qs, many=True).data
        if tier in ("SUPER_ADMIN", "ADMIN", "STAFF"):
            data = [u for u in data if u["tier"] == tier]
        return Response(data)

    @transaction.atomic
    def create(self, request):
        is_super = bool(request.data.get("is_superuser", False))
        if is_super and not request.user.is_superuser:
            raise PermissionDenied("Only active Super Admins can create Super Admin accounts.")
        username = (request.data.get("username") or "").strip()
        email = (request.data.get("email") or "").strip()
        password = request.data.get("password") or "TempPass@1234"
        if not username or not email:
            return Response({"detail": "username and email are required."}, status=status.HTTP_400_BAD_REQUEST)
        if User.objects.filter(Q(username=username) | Q(email=email)).exists():
            return Response({"detail": "Username or email already exists."}, status=status.HTTP_400_BAD_REQUEST)

        user = User.objects.create_user(
            username=username,
            email=email,
            password=password,
            full_name=(request.data.get("full_name") or "").strip(),
            department=request.data.get("department", ""),
            is_superuser=is_super,
            is_staff=is_super,
            mfa_enabled=bool(request.data.get("mfa_enabled", is_super)),
            must_reset_password=bool(request.data.get("must_reset_password", True)),
        )
        company_id = request.data.get("company_id") or str(request.company.id)
        company = get_object_or_404(Company, id=company_id)
        role_id = request.data.get("role_id")
        if role_id:
            role = get_object_or_404(Role, id=role_id)
        else:
            role_code = "SUPER_ADMIN" if is_super else request.data.get("role_code", "ACCOUNTANT")
            spec = ROLE_PRESETS.get(role_code, ROLE_PRESETS["ACCOUNTANT"])
            role, _ = Role.objects.get_or_create(
                code=role_code,
                defaults={"name": spec["name"], "description": spec["description"], "permissions": spec["permissions"], "is_system": True},
            )

        if not request.user.is_superuser:
            actor_perms = set(request.company_membership.effective_permissions())
            missing = set(role.permissions or []) - actor_perms
            if missing:
                raise PermissionDenied("Cannot assign a role containing permissions you lack.")

        m = CompanyMembership.objects.create(
            user=user,
            company=company,
            role=role,
            data_scope=request.data.get("data_scope", CompanyMembership.DataScope.PLATFORM if is_super else CompanyMembership.DataScope.COMPANY),
            is_default=True,
            is_active=True,
        )
        m.roles.add(role)
        record_audit_event(
            company=company,
            actor=request.user,
            action="ADMIN_USER_CREATED",
            entity_type="User",
            entity_id=str(user.id),
            new_state={"username": user.username, "is_superuser": is_super, "role": role.code},
        )
        return Response(PlatformUserSerializer(user).data, status=status.HTTP_201_CREATED)

    def partial_update(self, request, pk=None):
        user = get_object_or_404(User, id=pk)
        if user.is_superuser and not request.user.is_superuser:
            raise PermissionDenied("Only Super Admins can modify Super Admin accounts.")
        active_supers = User.objects.filter(is_active=True, is_superuser=True).count()
        demoting_or_disabling = (
            user.is_superuser
            and active_supers <= 1
            and (request.data.get("is_active") is False or request.data.get("is_superuser") is False)
        )
        if demoting_or_disabling:
            return Response(
                {"detail": "Cannot disable or demote the last active Super Admin."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        if "is_superuser" in request.data and not request.user.is_superuser:
            raise PermissionDenied("Privilege escalation blocked.")

        for fld in ("full_name", "department", "email", "is_active", "is_superuser", "mfa_enabled", "must_reset_password"):
            if fld in request.data:
                setattr(user, fld, request.data[fld])
        user.save()
        if not user.is_active:
            CompanyMembership.objects.filter(user=user).update(auth_version=F("auth_version") + 1)
        record_audit_event(actor=request.user, action="ADMIN_USER_UPDATED", entity_type="User", entity_id=str(user.id), new_state={"is_active": user.is_active, "is_superuser": user.is_superuser})
        return Response(PlatformUserSerializer(user).data)

    @action(detail=True, methods=["post"], url_path="reset-password")
    def reset_password(self, request, pk=None):
        user = get_object_or_404(User, id=pk)
        if user.is_superuser and not request.user.is_superuser:
            raise PermissionDenied("Only Super Admins can reset another Super Admin's password.")
        new_pw = request.data.get("new_password") or "ResetPass@2026"
        user.set_password(new_pw)
        user.must_reset_password = True
        user.save(update_fields=["password", "must_reset_password"])
        CompanyMembership.objects.filter(user=user).update(auth_version=F("auth_version") + 1)
        record_audit_event(actor=request.user, action="USER_PASSWORD_RESET", entity_type="User", entity_id=str(user.id))
        return Response({"detail": f"Password reset and force-change enforced for {user.username}."})

    @action(detail=True, methods=["post"], url_path="force-logout")
    def force_logout(self, request, pk=None):
        user = get_object_or_404(User, id=pk)
        CompanyMembership.objects.filter(user=user).update(auth_version=F("auth_version") + 1)
        Device.objects.filter(user=user, status=Device.Status.ACTIVE).update(status=Device.Status.REVOKED)
        SecurityLoginEvent.objects.create(
            user=user,
            username_attempted=user.username,
            event_type=SecurityLoginEvent.EventType.SESSION_REVOKED,
            failure_reason=f"Forced logout by {request.user.username}",
        )
        return Response({"detail": f"All active sessions and devices revoked for {user.username}."})

    @action(detail=True, methods=["post"], url_path="assign-company")
    def assign_company(self, request, pk=None):
        user = get_object_or_404(User, id=pk)
        company = get_object_or_404(Company, id=request.data["company_id"])
        role = get_object_or_404(Role, id=request.data["role_id"])
        if not request.user.is_superuser:
            missing = set(role.permissions or []) - set(request.company_membership.effective_permissions())
            if missing:
                raise PermissionDenied("Cannot grant permissions you do not possess.")
        m, _ = CompanyMembership.objects.update_or_create(
            user=user,
            company=company,
            defaults={
                "role": role,
                "data_scope": request.data.get("data_scope", CompanyMembership.DataScope.COMPANY),
                "is_active": True,
            },
        )
        m.roles.set([role])
        if request.data.get("branch_ids"):
            m.branches.set(Branch.objects.filter(company=company, id__in=request.data["branch_ids"]))
        m.auth_version += 1
        m.save(update_fields=["auth_version"])
        return Response(PlatformUserSerializer(user).data)


class SystemConfigView(AdminPermissionMixin, APIView):
    action_permissions = {
        "get": [Permissions.SYSTEM_CONFIG_MANAGE, Permissions.SYSTEM_VIEW, Permissions.COMPANY_MANAGE],
        "put": Permissions.SYSTEM_CONFIG_MANAGE,
    }

    def get(self, request):
        category = request.query_params.get("category")
        scope_company = request.company if request.query_params.get("scope", "COMPANY") == "COMPANY" else None
        configs = SystemConfigurationService.get_effective_configs(company=scope_company, category=category)
        history = ConfigurationHistorySerializer(
            ConfigurationHistory.objects.all()[:40], many=True
        ).data
        return Response({"configs": configs, "history": history})

    def put(self, request):
        scope = request.data.get("scope", "GLOBAL")
        if scope == "GLOBAL" and not (
            request.user.is_superuser or Permissions.SYSTEM_CONFIG_MANAGE in request.company_membership.effective_permissions()
        ):
            raise PermissionDenied("Insufficient privileges for Global configuration.")
        try:
            saved = SystemConfigurationService.upsert_config(
                scope=scope,
                company=request.company if scope == "COMPANY" else None,
                category=request.data["category"],
                key=request.data["key"],
                value=request.data.get("value"),
                is_sensitive=bool(request.data.get("is_sensitive", False)),
                label=request.data.get("label", ""),
                actor=request.user,
                reason=request.data.get("reason", ""),
            )
            return Response(saved)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class SystemConfigTestView(AdminPermissionMixin, APIView):
    required_permission = Permissions.SYSTEM_CONFIG_MANAGE

    def post(self, request):
        kind = request.data.get("kind", "storage")
        if kind == "email":
            return Response(SystemConfigurationService.test_smtp_config(company=request.company))
        return Response(SystemConfigurationService.test_storage_target(company=request.company))


class ApiIntegrationKeyViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "list": Permissions.SYSTEM_CONFIG_MANAGE,
        "create": Permissions.SYSTEM_CONFIG_MANAGE,
        "revoke": Permissions.SYSTEM_CONFIG_MANAGE,
    }

    def list(self, request):
        qs = ApiIntegrationKey.objects.filter(Q(company=request.company) | Q(company__isnull=True))
        return Response(ApiIntegrationKeySerializer(qs, many=True).data)

    def create(self, request):
        res = ApiIntegrationService.create_key(
            company=None if request.data.get("is_global") else request.company,
            name=request.data["name"],
            service_type=request.data.get("service_type", ApiIntegrationKey.ServiceType.CUSTOM_API),
            endpoint_url=request.data.get("endpoint_url", ""),
            scopes=request.data.get("scopes", []),
            actor=request.user,
        )
        return Response(res, status=status.HTTP_201_CREATED)

    @action(detail=True, methods=["post"])
    def revoke(self, request, pk=None):
        key = get_object_or_404(ApiIntegrationKey, id=pk)
        key.is_active = False
        key.save(update_fields=["is_active"])
        return Response(ApiIntegrationKeySerializer(key).data)


class SecurityEventsAndLogsViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "login_events": Permissions.AUDIT_READ,
        "activity_logs": Permissions.AUDIT_READ,
    }

    @action(detail=False, methods=["get"], url_path="login-events")
    def login_events(self, request):
        qs = SecurityLoginEvent.objects.all()
        ev_type = request.query_params.get("event_type")
        if ev_type:
            qs = qs.filter(event_type=ev_type)
        return Response(SecurityLoginEventSerializer(qs[:150], many=True).data)

    @action(detail=False, methods=["get"], url_path="activity-logs")
    def activity_logs(self, request):
        qs = AuditEvent.objects.select_related("actor", "company").all()
        if not request.user.is_superuser:
            qs = qs.filter(Q(company=request.company) | Q(company__isnull=True))
        action_f = request.query_params.get("action")
        if action_f:
            qs = qs.filter(action__icontains=action_f)
        return Response(AdminAuditEventSerializer(qs[:150], many=True).data)


class CriticalOperationViewSet(AdminPermissionMixin, viewsets.ViewSet):
    action_permissions = {
        "list": Permissions.SYSTEM_MANAGE,
        "approve": Permissions.SUPER_ADMIN_MANAGE,
        "reject": Permissions.SUPER_ADMIN_MANAGE,
    }

    def list(self, request):
        return Response(CriticalOperationRequestSerializer(CriticalOperationRequest.objects.all()[:50], many=True).data)

    @action(detail=True, methods=["post"])
    def approve(self, request, pk=None):
        if not request.user.is_superuser:
            raise PermissionDenied("Only Super Admins can approve critical platform operations.")
        obj = get_object_or_404(CriticalOperationRequest, id=pk)
        if obj.requested_by_id == request.user.id:
            return Response(
                {"detail": "Maker-checker violation: requester cannot approve their own critical operation."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        if obj.status != CriticalOperationRequest.Status.PENDING:
            return Response({"detail": "Request is no longer pending."}, status=status.HTTP_400_BAD_REQUEST)
        obj.status = CriticalOperationRequest.Status.APPROVED
        obj.approved_by = request.user
        obj.decided_at = timezone.now()
        obj.decision_note = request.data.get("note", "")
        obj.save()
        return Response(CriticalOperationRequestSerializer(obj).data)

    @action(detail=True, methods=["post"])
    def reject(self, request, pk=None):
        if not request.user.is_superuser:
            raise PermissionDenied("Only Super Admins can reject critical platform operations.")
        obj = get_object_or_404(CriticalOperationRequest, id=pk)
        obj.status = CriticalOperationRequest.Status.REJECTED
        obj.approved_by = request.user
        obj.decided_at = timezone.now()
        obj.decision_note = request.data.get("note", "")
        obj.save()
        return Response(CriticalOperationRequestSerializer(obj).data)


class AdminReportExportView(AdminPermissionMixin, APIView):
    required_permission = [Permissions.SYSTEM_VIEW, Permissions.AUDIT_READ, Permissions.BACKUP_MANAGE]

    def get(self, request, report_key: str):
        fmt = (request.query_params.get("export_format") or request.query_params.get("format") or "json").lower()
        try:
            if fmt == "pdf":
                pdf_bytes = AdminReportingService.render_pdf(report_key, company=request.company)
                resp = HttpResponse(pdf_bytes, content_type="application/pdf")
                resp["Content-Disposition"] = f'attachment; filename="{report_key}.pdf"'
                return resp
            if fmt == "xlsx":
                xlsx_bytes = AdminReportingService.render_xlsx(report_key, company=request.company)
                resp = HttpResponse(
                    xlsx_bytes,
                    content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                )
                resp["Content-Disposition"] = f'attachment; filename="{report_key}.xlsx"'
                return resp
            return Response(AdminReportingService.build_report_dataset(report_key, company=request.company))
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)

