# src/ihyee/async_client.py
"""Asynchronous ihyee API client."""
from __future__ import annotations

from typing import Any, List, Optional

import httpx

from ihyee.client import _build_payload, _handle_errors, _resolve_api_key
from ihyee.models import FetchResponse, SearchResponse


class AsyncIhyee:
    """Asynchronous client for the ihyee web intelligence API.

    Usage::

        from ihyee import AsyncIhyee

        async with AsyncIhyee(api_key="your_key") as client:
            results = await client.search("transformer architecture")
            print(results.content[0].text.summary)
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = "https://ihyee.delta-telematics.ca",
        timeout: float = 60.0,
    ) -> None:
        resolved_key = _resolve_api_key(api_key)
        self._http = httpx.AsyncClient(
            base_url=base_url,
            headers={"Authorization": f"Bearer {resolved_key}"},
            timeout=timeout,
        )

    async def search(
        self,
        query: str,
        *,
        max_results: int = 5,
        content_mode: str = "both",
        render: bool = False,
        summarize_sentences: int = 10,
        before: Optional[str] = None,
        after: Optional[str] = None,
        date_restrict: Optional[str] = None,
        must_have: Optional[str] = None,
        intext: Optional[str] = None,
        and_condition: Optional[str] = None,
    ) -> SearchResponse:
        """Search the web and return extracted content from top results."""
        payload = _build_payload(
            {"query": query, "max_results": max_results, "content_mode": content_mode,
             "render": render, "summarize_sentences": summarize_sentences},
            before=before, after=after, date_restrict=date_restrict,
            must_have=must_have, intext=intext, and_condition=and_condition,
        )
        response = await self._http.post("/v1/search", json=payload)
        _handle_errors(response)
        return SearchResponse.model_validate(response.json())

    async def fetch(
        self,
        urls: List[str],
        *,
        content_mode: str = "both",
        render: bool = False,
        summarize_sentences: int = 10,
    ) -> FetchResponse:
        """Fetch and extract content from specific URLs."""
        payload = {
            "urls": urls,
            "content_mode": content_mode,
            "render": render,
            "summarize_sentences": summarize_sentences,
        }
        response = await self._http.post("/v1/fetch", json=payload)
        _handle_errors(response)
        return FetchResponse.model_validate(response.json())

    async def render(
        self,
        url: str,
        *,
        wait_for: str = "networkidle",
        wait_selector: Optional[str] = None,
        timeout_ms: int = 30000,
        content_mode: str = "both",
        summarize_sentences: int = 10,
    ) -> FetchResponse:
        """Force full Playwright render of a URL."""
        payload = _build_payload(
            {"url": url, "wait_for": wait_for, "timeout_ms": timeout_ms,
             "content_mode": content_mode, "summarize_sentences": summarize_sentences},
            wait_selector=wait_selector,
        )
        response = await self._http.post("/v1/render", json=payload)
        _handle_errors(response)
        return FetchResponse.model_validate(response.json())

    async def close(self) -> None:
        """Close the HTTP client."""
        await self._http.aclose()

    async def __aenter__(self) -> AsyncIhyee:
        return self

    async def __aexit__(self, *args: Any) -> None:
        await self.close()
