"""API 请求处理器"""

from typing import Dict, Any, Optional
from playwright.sync_api import APIRequestContext, BrowserContext

from ..reference import GSTORE, INFO, set_element_value


class RequestHandler:
    """API 请求处理器

    使用 Playwright 的 APIRequestContext 发送 HTTP 请求。
    """

    def __init__(self, context: Optional[BrowserContext] = None, base_url: str = ''):
        """初始化请求处理器

        Args:
            context: BrowserContext 实例
            base_url: 基础 URL
        """
        self._context = context or GSTORE.get('context')
        self._base_url = base_url
        self._request: Optional[APIRequestContext] = None
        self._default_headers: Dict[str, str] = {}
        self._last_response: Optional[Dict[str, Any]] = None

    def create_request_context(
        self,
        base_url: str = None,
        extra_headers: Dict[str, str] = None
    ) -> None:
        """创建请求上下文

        Args:
            base_url: 基础 URL
            extra_headers: 额外请求头
        """
        if self._context:
            options = {}
            if base_url:
                options['base_url'] = base_url
            if extra_headers:
                options['extra_http_headers'] = extra_headers

            self._request = self._context.request

    def set_default_headers(self, headers: Dict[str, str]) -> None:
        """设置默认请求头

        Args:
            headers: 请求头字典
        """
        self._default_headers.update(headers)

    def get(
        self,
        url: str,
        params: Dict[str, Any] = None,
        headers: Dict[str, str] = None
    ) -> Dict[str, Any]:
        """GET 请求

        Args:
            url: 请求 URL
            params: 查询参数
            headers: 请求头

        Returns:
            Dict: 响应数据
        """
        return self._request_method('get', url, params=params, headers=headers)

    def post(
        self,
        url: str,
        data: Any = None,
        json_data: Dict = None,
        headers: Dict[str, str] = None
    ) -> Dict[str, Any]:
        """POST 请求

        Args:
            url: 请求 URL
            data: 表单数据
            json_data: JSON 数据
            headers: 请求头

        Returns:
            Dict: 响应数据
        """
        return self._request_method('post', url, data=data, json_data=json_data, headers=headers)

    def put(
        self,
        url: str,
        data: Any = None,
        json_data: Dict = None,
        headers: Dict[str, str] = None
    ) -> Dict[str, Any]:
        """PUT 请求

        Args:
            url: 请求 URL
            data: 表单数据
            json_data: JSON 数据
            headers: 请求头

        Returns:
            Dict: 响应数据
        """
        return self._request_method('put', url, data=data, json_data=json_data, headers=headers)

    def delete(
        self,
        url: str,
        headers: Dict[str, str] = None
    ) -> Dict[str, Any]:
        """DELETE 请求

        Args:
            url: 请求 URL
            headers: 请求头

        Returns:
            Dict: 响应数据
        """
        return self._request_method('delete', url, headers=headers)

    def patch(
        self,
        url: str,
        data: Any = None,
        json_data: Dict = None,
        headers: Dict[str, str] = None
    ) -> Dict[str, Any]:
        """PATCH 请求

        Args:
            url: 请求 URL
            data: 表单数据
            json_data: JSON 数据
            headers: 请求头

        Returns:
            Dict: 响应数据
        """
        return self._request_method('patch', url, data=data, json_data=json_data, headers=headers)

    def _request_method(
        self,
        method: str,
        url: str,
        params: Dict[str, Any] = None,
        data: Any = None,
        json_data: Dict = None,
        headers: Dict[str, str] = None
    ) -> Dict[str, Any]:
        """发送请求

        Args:
            method: 请求方法
            url: 请求 URL
            params: 查询参数
            data: 表单数据
            json_data: JSON 数据
            headers: 请求头

        Returns:
            Dict: 响应数据
        """
        if not self._request and self._context:
            self._request = self._context.request

        if not self._request:
            raise RuntimeError("请求上下文未初始化")

        # 合并请求头
        final_headers = {**self._default_headers}
        if headers:
            final_headers.update(headers)

        # 构建完整 URL
        full_url = f"{self._base_url}{url}" if self._base_url and not url.startswith('http') else url

        # 构建请求参数
        request_kwargs = {
            'headers': final_headers if final_headers else None,
        }

        if params:
            request_kwargs['params'] = params
        if data:
            request_kwargs['data'] = data
        if json_data:
            request_kwargs['data'] = json_data

        INFO(f"API {method.upper()}: {full_url}")

        # 发送请求
        request_method = getattr(self._request, method)
        response = request_method(full_url, **{k: v for k, v in request_kwargs.items() if v is not None})

        # 解析响应
        result = {
            'status': response.status,
            'status_text': response.status_text,
            'headers': dict(response.headers),
            'url': response.url,
        }

        # 尝试解析 JSON
        try:
            result['json'] = response.json()
        except Exception:
            result['text'] = response.text()

        self._last_response = result
        INFO(f"API 响应: {response.status} {response.status_text}")

        return result

    @property
    def last_response(self) -> Optional[Dict[str, Any]]:
        """获取最后一次响应"""
        return self._last_response

    def dispose(self) -> None:
        """释放资源"""
        if self._request:
            self._request.dispose()
            self._request = None
