"""Search API 资源封装"""

from typing import Optional, List
from .base import Resource
from ..models.search import (
    SearchRequest,
    SearchResponse,
    HighlightOptions,
    FullContentOptions,
)
from ..utils.constants import ENDPOINT_SEARCH


class SearchResource(Resource):
    """Search API 资源

    提供 Web 搜索功能
    """

    def search(
        self,
        query: str,
        count: Optional[int] = None,
        search_type: Optional[str] = None,
        include_domains: Optional[List[str]] = None,
        exclude_domains: Optional[List[str]] = None,
        include_text: Optional[List[str]] = None,
        exclude_text: Optional[List[str]] = None,
        time_basis: Optional[str] = None,
        start_time: Optional[str] = None,
        end_time: Optional[str] = None,
        highlight: Optional[HighlightOptions] = None,
        format: Optional[str] = None,
        safesearch: Optional[str] = None,
        full_content: Optional[FullContentOptions] = None,
        timeout: Optional[float] = None,
    ) -> SearchResponse:
        """执行 Web 搜索

        Args:
            query: 搜索查询字符串（必填，最多 500 字符）
            count: 返回结果数量（1-100，默认 5）
            search_type: 搜索类型（auto/keyword/semantic，默认 auto）
            include_domains: 包含的域名列表
            exclude_domains: 排除的域名列表
            include_text: 必须包含的文本列表
            exclude_text: 必须排除的文本列表
            time_basis: 时间基准（auto/published/crawled，默认 auto）
            start_time: 开始时间（ISO 8601 格式）
            end_time: 结束时间（ISO 8601 格式）
            highlight: 高亮选项配置
            format: 内容格式（text/markdown，默认 text）
            safesearch: 安全搜索级别（off/strict，默认 strict）
            full_content: 完整内容选项配置
            timeout: 请求超时时间（秒），覆盖默认值

        Returns:
            SearchResponse: 搜索响应对象

        Raises:
            OctenValidationError: 参数验证失败
            OctenAPIError: API 请求失败
            OctenTimeoutError: 请求超时

        Example:
            >>> from octen import Octen
            >>> client = Octen(api_key="your-api-key")
            >>> response = client.search.search(
            ...     query="Python programming",
            ...     count=10,
            ...     search_type="semantic"
            ... )
            >>> for result in response.results:
            ...     print(result['title'], result['url'])
        """
        # 创建并验证请求模型
        request = SearchRequest(
            query=query,
            count=count,
            search_type=search_type,
            include_domains=include_domains,
            exclude_domains=exclude_domains,
            include_text=include_text,
            exclude_text=exclude_text,
            time_basis=time_basis,
            start_time=start_time,
            end_time=end_time,
            highlight=highlight,
            format=format,
            safesearch=safesearch,
            full_content=full_content,
        )

        # 调用 HTTP 客户端
        response_data = self._client.request(
            method="POST",
            endpoint=ENDPOINT_SEARCH,
            json=request.model_dump(exclude_none=True),
            timeout=timeout,
        )

        # 解析并返回响应
        return SearchResponse(**response_data)

    def simple_search(
        self,
        query: str,
        count: int = 5,
        timeout: Optional[float] = None,
    ) -> SearchResponse:
        """简化的搜索接口

        使用默认参数执行快速搜索

        Args:
            query: 搜索查询字符串
            count: 返回结果数量（默认 5）
            timeout: 请求超时时间（秒）

        Returns:
            SearchResponse: 搜索响应对象

        Example:
            >>> response = client.search.simple_search("Python", count=5)
        """
        return self.search(query=query, count=count, timeout=timeout)
