"""
基础HTTP请求模块
提供统一的HTTP请求接口
"""

import requests
from typing import Any, Dict, Optional
from .session import session


class BaseClient:
    """基础HTTP客户端"""
    
    def __init__(self, verify_ssl: bool = False):
        """
        初始化客户端
        
        Args:
            verify_ssl: 是否验证SSL证书（默认False，适合开发环境）
        """
        self.session = requests.Session()
        self.verify_ssl = verify_ssl
        
        if not verify_ssl:
            # 禁用SSL警告
            requests.packages.urllib3.disable_warnings(
                requests.packages.urllib3.exceptions.InsecureRequestWarning
            )
            self.session.verify = False
    
    def _get_headers(self, token: Optional[str]) -> Dict[str, str]:
        """
        构建请求头
        
        Args:
            token: 访问令牌
            
        Returns:
            请求头字典
        """
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        if token:
            headers['Authorization'] = f'token {token}'
        return headers
    
    def _build_url(self, base_url: str, endpoint: str) -> str:
        """
        构建完整URL
        
        Args:
            base_url: 基础URL
            endpoint: API端点
            
        Returns:
            完整URL
        """
        base = base_url.rstrip('/')
        path = endpoint.lstrip('/')
        return f"{base}/{path}"
    
    def request(self, endpoint: str, method: str = 'GET', 
                data: Optional[Dict] = None) -> Dict[str, Any]:
        """
        发送HTTP请求（使用会话配置）
        
        Args:
            endpoint: API端点
            method: HTTP方法
            data: 请求数据
            
        Returns:
            响应JSON数据
            
        Raises:
            Exception: 请求失败时
        """
        url, token = session.get_session()
        return self.request_with_auth(url, token, endpoint, method, data)
    
    def request_with_auth(self, url: str, token: Optional[str], endpoint: str,
                         method: str = 'GET', data: Optional[Dict] = None) -> Dict[str, Any]:
        """
        发送HTTP请求（显式指定认证信息）
        
        Args:
            url: 服务器地址
            token: 访问令牌
            endpoint: API端点
            method: HTTP方法
            data: 请求数据
            
        Returns:
            响应JSON数据
            
        Raises:
            Exception: 请求失败时
        """
        full_url = self._build_url(url, endpoint)
        headers = self._get_headers(token)
        
        try:
            if method.upper() == 'GET':
                response = self.session.get(full_url, headers=headers)
            elif method.upper() == 'POST':
                response = self.session.post(full_url, headers=headers, json=data)
            elif method.upper() == 'PUT':
                response = self.session.put(full_url, headers=headers, json=data)
            elif method.upper() == 'DELETE':
                response = self.session.delete(full_url, headers=headers)
            else:
                raise ValueError(f"不支持的HTTP方法: {method}")
            
            response.raise_for_status()
            
            # DELETE请求可能返回空响应
            if method.upper() == 'DELETE' and not response.content:
                return {"success": True, "message": "删除成功"}
            
            return response.json()
        except requests.exceptions.JSONDecodeError as e:
            # 如果响应不是JSON，但状态码正常，返回成功
            if response.status_code < 400:
                return {"success": True, "message": "操作成功"}
            raise Exception(f"请求失败: {str(e)}")
        except requests.exceptions.RequestException as e:
            raise Exception(f"请求失败: {str(e)}")


# 全局客户端实例
client = BaseClient(verify_ssl=False)
