from http import HTTPStatus
from typing import Any

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.document_search_sort_by import DocumentSearchSortBy
from ...models.error import Error
from ...models.search_result import SearchResult
from ...types import UNSET, Response, Unset


def _get_kwargs(
    *,
    search_query: str,
    search_offset: float | Unset = 0.0,
    search_limit: float | Unset = 10.0,
    stack_id: str | Unset = UNSET,
    format_: str | Unset = UNSET,
    field: str | Unset = UNSET,
    value: str | Unset = UNSET,
    sort_by: DocumentSearchSortBy | Unset = UNSET,
) -> dict[str, Any]:

    params: dict[str, Any] = {}

    params["searchQuery"] = search_query

    params["searchOffset"] = search_offset

    params["searchLimit"] = search_limit

    params["stackId"] = stack_id

    params["format"] = format_

    params["field"] = field

    params["value"] = value

    json_sort_by: str | Unset = UNSET
    if not isinstance(sort_by, Unset):
        json_sort_by = sort_by.value

    params["sortBy"] = json_sort_by

    params = {k: v for k, v in params.items() if v is not UNSET and v is not None}

    _kwargs: dict[str, Any] = {
        "method": "get",
        "url": "/document/search",
        "params": params,
    }

    return _kwargs


def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Error | SearchResult | None:
    if response.status_code == 200:
        response_200 = SearchResult.from_dict(response.json())

        return response_200

    if response.status_code == 400:
        response_400 = Error.from_dict(response.json())

        return response_400

    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


def _build_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> Response[Error | SearchResult]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    *,
    client: AuthenticatedClient,
    search_query: str,
    search_offset: float | Unset = 0.0,
    search_limit: float | Unset = 10.0,
    stack_id: str | Unset = UNSET,
    format_: str | Unset = UNSET,
    field: str | Unset = UNSET,
    value: str | Unset = UNSET,
    sort_by: DocumentSearchSortBy | Unset = UNSET,
) -> Response[Error | SearchResult]:
    """Search Documents

     Search documents using Elasticsearch

    Args:
        search_query (str):
        search_offset (float | Unset):  Default: 0.0.
        search_limit (float | Unset):  Default: 10.0.
        stack_id (str | Unset):
        format_ (str | Unset):
        field (str | Unset):
        value (str | Unset):
        sort_by (DocumentSearchSortBy | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[Error | SearchResult]
    """

    kwargs = _get_kwargs(
        search_query=search_query,
        search_offset=search_offset,
        search_limit=search_limit,
        stack_id=stack_id,
        format_=format_,
        field=field,
        value=value,
        sort_by=sort_by,
    )

    response = client.get_httpx_client().request(
        **kwargs,
    )

    return _build_response(client=client, response=response)


def sync(
    *,
    client: AuthenticatedClient,
    search_query: str,
    search_offset: float | Unset = 0.0,
    search_limit: float | Unset = 10.0,
    stack_id: str | Unset = UNSET,
    format_: str | Unset = UNSET,
    field: str | Unset = UNSET,
    value: str | Unset = UNSET,
    sort_by: DocumentSearchSortBy | Unset = UNSET,
) -> Error | SearchResult | None:
    """Search Documents

     Search documents using Elasticsearch

    Args:
        search_query (str):
        search_offset (float | Unset):  Default: 0.0.
        search_limit (float | Unset):  Default: 10.0.
        stack_id (str | Unset):
        format_ (str | Unset):
        field (str | Unset):
        value (str | Unset):
        sort_by (DocumentSearchSortBy | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Error | SearchResult
    """

    return sync_detailed(
        client=client,
        search_query=search_query,
        search_offset=search_offset,
        search_limit=search_limit,
        stack_id=stack_id,
        format_=format_,
        field=field,
        value=value,
        sort_by=sort_by,
    ).parsed


async def asyncio_detailed(
    *,
    client: AuthenticatedClient,
    search_query: str,
    search_offset: float | Unset = 0.0,
    search_limit: float | Unset = 10.0,
    stack_id: str | Unset = UNSET,
    format_: str | Unset = UNSET,
    field: str | Unset = UNSET,
    value: str | Unset = UNSET,
    sort_by: DocumentSearchSortBy | Unset = UNSET,
) -> Response[Error | SearchResult]:
    """Search Documents

     Search documents using Elasticsearch

    Args:
        search_query (str):
        search_offset (float | Unset):  Default: 0.0.
        search_limit (float | Unset):  Default: 10.0.
        stack_id (str | Unset):
        format_ (str | Unset):
        field (str | Unset):
        value (str | Unset):
        sort_by (DocumentSearchSortBy | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[Error | SearchResult]
    """

    kwargs = _get_kwargs(
        search_query=search_query,
        search_offset=search_offset,
        search_limit=search_limit,
        stack_id=stack_id,
        format_=format_,
        field=field,
        value=value,
        sort_by=sort_by,
    )

    response = await client.get_async_httpx_client().request(**kwargs)

    return _build_response(client=client, response=response)


async def asyncio(
    *,
    client: AuthenticatedClient,
    search_query: str,
    search_offset: float | Unset = 0.0,
    search_limit: float | Unset = 10.0,
    stack_id: str | Unset = UNSET,
    format_: str | Unset = UNSET,
    field: str | Unset = UNSET,
    value: str | Unset = UNSET,
    sort_by: DocumentSearchSortBy | Unset = UNSET,
) -> Error | SearchResult | None:
    """Search Documents

     Search documents using Elasticsearch

    Args:
        search_query (str):
        search_offset (float | Unset):  Default: 0.0.
        search_limit (float | Unset):  Default: 10.0.
        stack_id (str | Unset):
        format_ (str | Unset):
        field (str | Unset):
        value (str | Unset):
        sort_by (DocumentSearchSortBy | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Error | SearchResult
    """

    return (
        await asyncio_detailed(
            client=client,
            search_query=search_query,
            search_offset=search_offset,
            search_limit=search_limit,
            stack_id=stack_id,
            format_=format_,
            field=field,
            value=value,
            sort_by=sort_by,
        )
    ).parsed
