#!/usr/bin/env python
# @Project ：django_base_ai
# @File    : safety_check_record.py
# @Author  : cx
# @Time    : 11/2/2025
# @Desc    : 安全检测记录相关接口。
import logging
import time

from django_celery_beat.models import PeriodicTask
from django_restql.fields import DynamicSerializerMethodField
from rest_framework.decorators import action

from django_base_ai.system.models import SafetyCheckRecord
from django_base_ai.utils.json_response import DetailResponse
from django_base_ai.utils.serializers import CustomModelSerializer
from django_base_ai.utils.viewset import CustomModelViewSet

logger = logging.getLogger(__name__)


class SafetyCheckRecordSerializer(CustomModelSerializer):
    cron = DynamicSerializerMethodField()

    def get_cron(self, instance, parsed_query):
        info = []
        periodic_tasks = PeriodicTask.objects.filter(task="celery_tasks.tasks.periodic_safety_check")
        for p_task in periodic_tasks:
            info.append(
                {
                    "id": p_task.crontab.id,
                    "info": [
                        p_task.crontab.minute,
                        p_task.crontab.hour,
                        p_task.crontab.day_of_month,
                        p_task.crontab.month_of_year,
                        p_task.crontab.day_of_week,
                    ],
                }
            )
        return info

    class Meta:
        model = SafetyCheckRecord
        fields = "__all__"
        read_only_fields = ["id"]


class SafetyCheckRecordViewSet(CustomModelViewSet):
    """
    项目自检
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = SafetyCheckRecord.objects.order_by("-create_datetime")
    serializer_class = SafetyCheckRecordSerializer
    extra_filter_backends = []

    # 项目安全手动检查
    @action(methods=["get"], detail=False)
    def check(self, request):
        from django_base_ai.utils.safety_check import SafetyCheck

        start = time.time()
        safety_obj = SafetyCheck().check()
        end = time.time()
        data = {
            "pkg_count": safety_obj.pkg_count,
            "vulnerabilities_count": safety_obj.vulnerabilities_count,
            "vulnerabilities": safety_obj.vulnerabilities,
        }
        return DetailResponse(msg=f"漏洞检查完成，耗时{end - start}秒", data=data)
