from __future__ import annotations

import httpx

from .models import *


class SearchSearchAPI:
    """API endpoints for Search."""

    def __init__(self, client: httpx.AsyncClient):
        """Initialize sub-client with shared httpx client."""
        self._client = client

    async def list(self) -> list[SearchRequestList]:
        """
        List search history

        List search history for the current API key. Returns the last 100
        records.
        """
        url = "/api/search/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return [SearchRequestList.model_validate(item) for item in response.json()]


    async def fetch_create(self, data: URLFetchRequest) -> SearchResponse:
        """
        Fetch and analyze URL

        Fetch and analyze URL content using Claude.
        """
        url = "/api/search/fetch/"
        response = await self._client.post(url, json=data.model_dump(exclude_unset=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return SearchResponse.model_validate(response.json())


    async def query_create(self, data: SearchQueryRequest) -> SearchResponse:
        """
        Execute web search

        Execute a web search using Anthropic's web_search tool.
        """
        url = "/api/search/query/"
        response = await self._client.post(url, json=data.model_dump(exclude_unset=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return SearchResponse.model_validate(response.json())


