from __future__ import annotations

import httpx

from .models import (
    AsyncResearchResponse,
    JobStatus,
    ResearchRequestList,
    ResearchRequestRequest,
    ResearchResponse,
    SearchRequestRequest,
)


class ResearchResearchAPI:
    """API endpoints for Research."""

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

    async def list(
        self,
        ordering: str | None = None,
        search: str | None = None,
    ) -> list[ResearchRequestList]:
        """
        List research history

        List research history for the current API key.
        """
        url = "/api/research/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "search": search,
            }.items() if v is not None
        }
        response = await self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return [ResearchRequestList.model_validate(item) for item in response.json()]


    async def cancel_create(self, uuid: str) -> None:
        """
        Cancel job

        Cancel a queued or running research/search job.
        """
        url = f"/api/research/{uuid}/cancel/"
        response = await self._client.post(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return None


    async def results_retrieve(self, uuid: str) -> ResearchResponse:
        """
        Get results

        Get full results of a completed research/search job.
        """
        url = f"/api/research/{uuid}/results/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return ResearchResponse.model_validate(response.json())


    async def status_retrieve(self, uuid: str) -> JobStatus:
        """
        Get job status

        Poll status of an async research/search job.
        """
        url = f"/api/research/{uuid}/status/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return JobStatus.model_validate(response.json())


    async def research_create(self, data: ResearchRequestRequest) -> AsyncResearchResponse:
        """
        Execute research (async)

        Queue full pipeline: search → crawl → LLM summarize. Returns 202 with
        job_id.
        """
        url = "/api/research/research/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return AsyncResearchResponse.model_validate(response.json())


    async def search_create(self, data: SearchRequestRequest) -> AsyncResearchResponse:
        """
        Execute search (async)

        Queue Serper search. Returns 202 with job_id for polling, or 200 if sync
        fallback.
        """
        url = "/api/research/search/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return AsyncResearchResponse.model_validate(response.json())


