# apps/core/api/secret_key_api.py
import logging
import threading

from apps.core.decorators import require_security_code
from apps.core.services.django_sys import uWSGI_Reload
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

logger = logging.getLogger(__name__)


def get_secret_manager():
    """
    延迟导入 SecretKeyManager，避免循环依赖
    """
    from apps.core.utils.secret_manager import secret_manager

    return secret_manager


@api_view(["POST"])
@permission_classes([IsAdminUser])
@require_security_code
def reset_secret_key(request):
    """
    重置 SECRET_KEY API
    权限：仅管理员 + 安全代码验证
    """
    # 记录操作日志
    user = request.user.username
    logger.info(f"用户 {user} 请求重置 SECRET_KEY")

    try:
        secret_manager = get_secret_manager()
        result = secret_manager.reset_secret_key()

        if result["success"]:
            logger.info(f"用户 {user} 成功重置 SECRET_KEY")

            # 异步重启 uWSGI
            reload_thread = threading.Thread(target=uWSGI_Reload, daemon=True)
            reload_thread.start()

            response_data = {
                "success": True,
                "message": result["message"],
                "warning": result["warning"],
                "restart_initiated": True,
                "note": "系统正在重启，新密钥将生效",
            }

            return Response(response_data, status=status.HTTP_200_OK)
        else:
            logger.error(f"用户 {user} 重置 SECRET_KEY 失败: {result['message']}")
            return Response(
                {"success": False, "message": result["message"]},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )

    except Exception as e:
        logger.error(f"重置 SECRET_KEY 时发生异常: {str(e)}", exc_info=True)
        return Response(
            {"success": False, "message": f"服务器内部错误: {str(e)}"},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
        )


@api_view(["POST"])
@permission_classes([IsAdminUser])
@require_security_code
def force_reset_secret_key(request):
    """
    强制重置 SECRET_KEY（即使密钥状态正常）
    权限：仅管理员 + 安全代码验证
    """
    user = request.user.username
    logger.warning(f"用户 {user} 请求强制重置 SECRET_KEY")

    try:
        secret_manager = get_secret_manager()
        result = secret_manager.rotate_secret_manual("强制重置")

        if result["success"]:
            logger.info(f"用户 {user} 强制重置 SECRET_KEY 成功")

            # 异步重启 uWSGI
            reload_thread = threading.Thread(target=uWSGI_Reload, daemon=True)
            reload_thread.start()

            return Response(
                {
                    "success": True,
                    "message": "SECRET_KEY 已强制重置",
                    "warning": result["warning"],
                    "restart_initiated": True,
                    "note": "系统正在重启，新密钥将生效",
                },
                status=status.HTTP_200_OK,
            )
        else:
            logger.error(f"用户 {user} 强制重置 SECRET_KEY 失败: {result['message']}")
            return Response(
                {"success": False, "message": result["message"]},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            )

    except Exception as e:
        logger.error(f"强制重置 SECRET_KEY 时发生异常: {str(e)}", exc_info=True)
        return Response(
            {"success": False, "message": f"服务器内部错误: {str(e)}"},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
        )


@api_view(["GET"])
@permission_classes([IsAdminUser])
def get_secret_key_info(request):
    """
    获取 SECRET_KEY 信息 API
    权限：仅管理员
    """
    try:
        secret_manager = get_secret_manager()
        secret_info = secret_manager.get_secret_info()

        # 安全处理：不返回实际的密钥内容
        safe_info = {
            "key_age_days": secret_info.get("key_age_days", 0),
            "status": secret_info.get("status", "unknown"),
            "using_default": secret_info.get("using_default", False),
            "from_env": secret_info.get("from_env", False),
            "consistent": secret_info.get("consistent", False),
            "last_rotation": secret_info.get("last_rotation"),
            "rotation_reason": secret_info.get("rotation_reason"),
            "key_length": secret_info.get("current_key_length", 0),
            "file_key_length": secret_info.get("file_key_length", 0),
            "key_hash": secret_info.get("key_hash", ""),
            "secret_file_exists": secret_info.get("secret_file_exists", False),
        }

        # 添加建议
        if safe_info["key_age_days"] > 90:
            safe_info["recommendation"] = "密钥已过期，建议立即轮换"
        elif safe_info["key_age_days"] > 80:
            safe_info["recommendation"] = "密钥即将过期，建议近期轮换"
        elif safe_info["using_default"]:
            safe_info["recommendation"] = "正在使用默认密钥，建议生成持久化密钥"
        elif not safe_info["consistent"]:
            safe_info["recommendation"] = "运行密钥与文件不一致，建议重启应用"
        else:
            safe_info["recommendation"] = "密钥状态良好"

        return Response(safe_info, status=status.HTTP_200_OK)

    except Exception as e:
        return Response(
            {"success": False, "message": f"获取密钥信息失败: {str(e)}"},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
        )


@api_view(["GET"])
def get_secret_key_status_public(request):
    """
    公开的SECRET_KEY状态API（不包含敏感信息）
    用于系统信息显示
    """
    try:
        secret_manager = get_secret_manager()
        secret_info = secret_manager.get_secret_info()

        # 只返回公开信息
        safe_info = {
            "key_age_days": secret_info.get("key_age_days", 0),
            "status": secret_info.get("status", "unknown"),
            "using_default": secret_info.get("using_default", False),
            "key_length": secret_info.get("current_key_length", 0),
            "need_reset": (
                secret_info.get("using_default", False) or secret_info.get("key_age_days", 0) > 90
            ),
        }

        return Response(safe_info, status=status.HTTP_200_OK)

    except Exception as e:
        return Response(
            {"success": False, "message": f"获取密钥状态失败: {str(e)}"},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
        )
