#!/usr/bin/env python
"""
@Project ：django_base_ai
@File    ：json_request.py
@Author  ：congxing.wang
@Date    ：2026/02/25
@Desc    ：JSON 解析与 HTTP 请求发送
"""

import logging
import time

import httpx

logger = logging.getLogger(__name__)


class ExecuteJsonRequest:
    def request(self, infos):
        start_time = time.time()
        reqmethod = infos.get("reqmethod", "GET")
        url = infos.get("url", "")
        headers = infos.get("headers", {})
        proxies = infos.get("proxies", {})
        payload = infos.get("payload", {})
        logger.debug("请求开始 %s %s", reqmethod, url)
        with httpx.Client(timeout=5) as client:
            client.verify = True if "https://" in url else False
            client.proxies = proxies if proxies else {}
            try:
                resp = client.request(reqmethod, url, headers=headers, data=payload)
                resp_result = resp.text if resp.status_code == 200 else str(resp.extensions)
                elapsed = time.time() - start_time
                logger.info("请求完成 %s %s status=%s elapsed=%.2fs", reqmethod, url, resp.status_code, elapsed)
                return True, resp_result, resp.status_code, elapsed
            except Exception as e:
                logger.warning("请求失败 %s %s: %s", reqmethod, url, e)
                return False, e.args, 500, 0


if __name__ == "__main__":
    infos = {
        "url": "http://0.0.0.0:8010/base/api/system/im_chat_question/ai_test/",
        "method": "GET",
        "headers": {"User-Agent": "Apifox/1.0.0 (https://apifox.com)"},
        "payload": {},
        "proxies": {},
    }
    send_request = ExecuteJsonRequest()
    flag, resp_result, status_code, run_tiem = send_request.request(infos)
    print(flag, resp_result, status_code, run_tiem)
