from http import HTTPStatus
from typing import Any

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.generate_annotations_request import GenerateAnnotationsRequest
from ...models.generate_annotations_response import GenerateAnnotationsResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import UNSET, Response, Unset


def _get_kwargs(
    *,
    body: GenerateAnnotationsRequest,
    config_ext_id: None | str | Unset = UNSET,
    workspace_key: str | Unset = "",
) -> dict[str, Any]:
    headers: dict[str, Any] = {}
    if not isinstance(workspace_key, Unset):
        headers["workspace-key"] = workspace_key

    params: dict[str, Any] = {}

    json_config_ext_id: None | str | Unset
    if isinstance(config_ext_id, Unset):
        json_config_ext_id = UNSET
    else:
        json_config_ext_id = config_ext_id
    params["config_ext_id"] = json_config_ext_id

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

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/api/document/doctag/generate",
        "params": params,
    }

    _kwargs["json"] = body.to_dict()

    headers["Content-Type"] = "application/json"

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> GenerateAnnotationsResponse | HTTPValidationError | None:
    if response.status_code == 202:
        response_202 = GenerateAnnotationsResponse.from_dict(response.json())

        return response_202

    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())

        return response_422

    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[GenerateAnnotationsResponse | HTTPValidationError]:
    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 | Client,
    body: GenerateAnnotationsRequest,
    config_ext_id: None | str | Unset = UNSET,
    workspace_key: str | Unset = "",
) -> Response[GenerateAnnotationsResponse | HTTPValidationError]:
    """Generate Doctags

     Generate AI annotations for documents using tag instructions.

    Creates doctags with AI-generated notes and citations for each (doc, tag) pair.
    Uses tag name + optional instruction as the question to answer about each document.

    Returns 202 Accepted immediately - processing happens in background.
    WebSocket notification sent when complete.

    Args:
        config_ext_id (None | str | Unset): Configuration to use for LLM
        workspace_key (str | Unset):  Default: ''.
        body (GenerateAnnotationsRequest): Request to generate AI annotations for documents using
            tag instructions.

            Creates a matrix of (docs × tags) annotations. Each tag's name is used as
            the instruction/question to answer about each document.

    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[GenerateAnnotationsResponse | HTTPValidationError]
    """

    kwargs = _get_kwargs(
        body=body,
        config_ext_id=config_ext_id,
        workspace_key=workspace_key,
    )

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

    return _build_response(client=client, response=response)


def sync(
    *,
    client: AuthenticatedClient | Client,
    body: GenerateAnnotationsRequest,
    config_ext_id: None | str | Unset = UNSET,
    workspace_key: str | Unset = "",
) -> GenerateAnnotationsResponse | HTTPValidationError | None:
    """Generate Doctags

     Generate AI annotations for documents using tag instructions.

    Creates doctags with AI-generated notes and citations for each (doc, tag) pair.
    Uses tag name + optional instruction as the question to answer about each document.

    Returns 202 Accepted immediately - processing happens in background.
    WebSocket notification sent when complete.

    Args:
        config_ext_id (None | str | Unset): Configuration to use for LLM
        workspace_key (str | Unset):  Default: ''.
        body (GenerateAnnotationsRequest): Request to generate AI annotations for documents using
            tag instructions.

            Creates a matrix of (docs × tags) annotations. Each tag's name is used as
            the instruction/question to answer about each document.

    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:
        GenerateAnnotationsResponse | HTTPValidationError
    """

    return sync_detailed(
        client=client,
        body=body,
        config_ext_id=config_ext_id,
        workspace_key=workspace_key,
    ).parsed


async def asyncio_detailed(
    *,
    client: AuthenticatedClient | Client,
    body: GenerateAnnotationsRequest,
    config_ext_id: None | str | Unset = UNSET,
    workspace_key: str | Unset = "",
) -> Response[GenerateAnnotationsResponse | HTTPValidationError]:
    """Generate Doctags

     Generate AI annotations for documents using tag instructions.

    Creates doctags with AI-generated notes and citations for each (doc, tag) pair.
    Uses tag name + optional instruction as the question to answer about each document.

    Returns 202 Accepted immediately - processing happens in background.
    WebSocket notification sent when complete.

    Args:
        config_ext_id (None | str | Unset): Configuration to use for LLM
        workspace_key (str | Unset):  Default: ''.
        body (GenerateAnnotationsRequest): Request to generate AI annotations for documents using
            tag instructions.

            Creates a matrix of (docs × tags) annotations. Each tag's name is used as
            the instruction/question to answer about each document.

    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[GenerateAnnotationsResponse | HTTPValidationError]
    """

    kwargs = _get_kwargs(
        body=body,
        config_ext_id=config_ext_id,
        workspace_key=workspace_key,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    *,
    client: AuthenticatedClient | Client,
    body: GenerateAnnotationsRequest,
    config_ext_id: None | str | Unset = UNSET,
    workspace_key: str | Unset = "",
) -> GenerateAnnotationsResponse | HTTPValidationError | None:
    """Generate Doctags

     Generate AI annotations for documents using tag instructions.

    Creates doctags with AI-generated notes and citations for each (doc, tag) pair.
    Uses tag name + optional instruction as the question to answer about each document.

    Returns 202 Accepted immediately - processing happens in background.
    WebSocket notification sent when complete.

    Args:
        config_ext_id (None | str | Unset): Configuration to use for LLM
        workspace_key (str | Unset):  Default: ''.
        body (GenerateAnnotationsRequest): Request to generate AI annotations for documents using
            tag instructions.

            Creates a matrix of (docs × tags) annotations. Each tag's name is used as
            the instruction/question to answer about each document.

    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:
        GenerateAnnotationsResponse | HTTPValidationError
    """

    return (
        await asyncio_detailed(
            client=client,
            body=body,
            config_ext_id=config_ext_id,
            workspace_key=workspace_key,
        )
    ).parsed
