#!/usr/bin/env python
"""
@Project ：django_base_ai
@File    ：execute_task.py
@Author  ：congxing.wang
@Date    ：2026/02/25
@Desc    ：定时任务执行与 HTTP 请求发送
"""

import time
from datetime import datetime

import httpx
from django_celery_beat.models import PeriodicTask

from django_base_ai.system.models import BaseTask, TaskRunHistory


class ExecuteRequestTask:
    def __init__(self, nid, pid=None):
        self.nid = nid
        self.pid = pid

    def request(self, client, infos):
        reqmethod = infos.get("reqmethod", "GET")
        url = infos.get("url", "")
        headers = infos.get("headers", {})
        payload = infos.get("payload", {})
        client.verify = True if "https://" in url else False
        try:
            resp = client.request(reqmethod, url, headers=headers, data=payload)
            resp_result = resp.text if resp.status_code == 200 else str(resp.extensions)
            return resp_result, resp.status_code
        except Exception as e:
            return e.args, 500

    def execute_task(self):
        task_management = BaseTask.objects.filter(id=self.nid, task_status=True).first()
        if task_management is None:
            return f"error={self.nid}"
        request_config = task_management.request_config
        limits = httpx.Limits(max_keepalive_connections=0, max_connections=100)
        with httpx.Client(limits=limits, timeout=5) as client:
            task_run_history = []
            for infos in request_config:
                start_time = datetime.now()
                url_name = infos.get("name", "")
                infos = {
                    "reqmethod": infos.get("reqmethod", "GET"),
                    "headers": infos.get("reqheaders", {}),
                    "url": infos.get("url", "#"),
                    "payload": infos.get("payload", {}),
                }
                resp_result, status_code = self.request(client, infos)
                if self.pid:
                    PeriodicTask.objects.filter(id=self.pid).update(last_run_at=datetime.now())
                task_run_history.append(
                    TaskRunHistory(
                        base_task_id=self.nid,
                        url_name=url_name,
                        start_time=start_time,
                        end_time=datetime.now(),
                        request_config=infos,
                        status_code=status_code,
                        run_result=resp_result,
                        periodic_task_id=self.pid,
                    )
                )
            if len(task_run_history):
                TaskRunHistory.objects.bulk_create(task_run_history)

    def run(self):
        start_time = time.time()
        self.execute_task()
        end_time = time.time()
        return end_time - start_time
