"""
HTTP工具函数模块
"""
from typing import Dict, Any, Optional
import httpx
from loguru import logger

async def make_http_request(
    url: str, 
    method: str = "GET", 
    params: Optional[Dict[str, Any]] = None,
    headers: Optional[Dict[str, Any]] = None,
    json_data: Optional[Dict[str, Any]] = None,
    timeout: float = 30.0
) -> Dict[str, Any]:
    """发送HTTP请求并处理响应
    
    Args:
        url: 请求URL
        method: 请求方法（GET, POST等）
        params: URL参数
        headers: 请求头
        json_data: POST请求的JSON数据
        timeout: 超时时间(秒)
        
    Returns:
        响应数据（字典）或包含错误信息的字典
    """
    default_headers = {
        "User-Agent": "MCP-Tools/1.0",
        "Accept": "application/json"
    }
    
    if headers:
        default_headers.update(headers)
    
    try:
        logger.debug(f"发送{method}请求: {url}")
        
        async with httpx.AsyncClient() as client:
            response = await client.request(
                method,
                url,
                params=params,
                headers=default_headers,
                json=json_data,
                timeout=timeout
            )
            
            logger.debug(f"收到响应: {response.status_code}")
            response.raise_for_status()
            
            # 尝试解析JSON
            try:
                return response.json()
            except Exception as json_err:
                logger.error(f"解析JSON失败: {str(json_err)}")
                return {"error": "无法解析响应JSON", "text": response.text[:500]}
                
    except httpx.HTTPStatusError as err:
        status_code = err.response.status_code
        logger.error(f"HTTP状态错误 {status_code}: {str(err)}")
        
        # 尝试解析错误响应
        try:
            error_json = err.response.json()
            return {"error": f"HTTP错误 {status_code}", "details": error_json}
        except:
            return {"error": f"HTTP错误 {status_code}", "message": str(err)}
            
    except httpx.RequestError as err:
        logger.error(f"请求错误: {str(err)}")
        return {"error": "请求错误", "message": str(err)}
        
    except Exception as err:
        logger.error(f"HTTP请求异常: {str(err)}")
        return {"error": "请求异常", "message": str(err)} 