from http import HTTPStatus
from typing import Any

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.body_ingest_file_async_v1_ingestion_file_async_post import BodyIngestFileAsyncV1IngestionFileAsyncPost
from ...models.http_validation_error import HTTPValidationError
from ...models.ingest_async_response import IngestAsyncResponse
from ...types import UNSET, Response, Unset


def _get_kwargs(
    *,
    body: BodyIngestFileAsyncV1IngestionFileAsyncPost,
    kb_id: None | str | Unset = UNSET,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}

    params: dict[str, Any] = {}

    json_kb_id: None | str | Unset
    if isinstance(kb_id, Unset):
        json_kb_id = UNSET
    else:
        json_kb_id = kb_id
    params["kb_id"] = json_kb_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": "/v1/ingestion/file/async",
        "params": params,
    }

    _kwargs["files"] = body.to_multipart()

    _kwargs["headers"] = headers
    return _kwargs


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

        return response_200

    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[HTTPValidationError | IngestAsyncResponse]:
    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,
    body: BodyIngestFileAsyncV1IngestionFileAsyncPost,
    kb_id: None | str | Unset = UNSET,
) -> Response[HTTPValidationError | IngestAsyncResponse]:
    """Ingest File Async

     [V2] Accepts a file for high-priority ingestion into the user's permanent knowledge base.
    1. Persists the file to the user's permanent S3 folder (e.g., files/<user_id>/).
    2. Stages a copy for the ingestion worker.
    3. Queues a job in Redis for the 'synced_files' collection.
    4. Logs the file in 'processed_files_log' to prevent duplicate ingestion by the nightly cron job.

    Args:
        kb_id (None | str | Unset): Optional knowledge base ID. If omitted, uses the caller's
            personal knowledge base.
        body (BodyIngestFileAsyncV1IngestionFileAsyncPost):

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

    kwargs = _get_kwargs(
        body=body,
        kb_id=kb_id,
    )

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

    return _build_response(client=client, response=response)


def sync(
    *,
    client: AuthenticatedClient,
    body: BodyIngestFileAsyncV1IngestionFileAsyncPost,
    kb_id: None | str | Unset = UNSET,
) -> HTTPValidationError | IngestAsyncResponse | None:
    """Ingest File Async

     [V2] Accepts a file for high-priority ingestion into the user's permanent knowledge base.
    1. Persists the file to the user's permanent S3 folder (e.g., files/<user_id>/).
    2. Stages a copy for the ingestion worker.
    3. Queues a job in Redis for the 'synced_files' collection.
    4. Logs the file in 'processed_files_log' to prevent duplicate ingestion by the nightly cron job.

    Args:
        kb_id (None | str | Unset): Optional knowledge base ID. If omitted, uses the caller's
            personal knowledge base.
        body (BodyIngestFileAsyncV1IngestionFileAsyncPost):

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

    return sync_detailed(
        client=client,
        body=body,
        kb_id=kb_id,
    ).parsed


async def asyncio_detailed(
    *,
    client: AuthenticatedClient,
    body: BodyIngestFileAsyncV1IngestionFileAsyncPost,
    kb_id: None | str | Unset = UNSET,
) -> Response[HTTPValidationError | IngestAsyncResponse]:
    """Ingest File Async

     [V2] Accepts a file for high-priority ingestion into the user's permanent knowledge base.
    1. Persists the file to the user's permanent S3 folder (e.g., files/<user_id>/).
    2. Stages a copy for the ingestion worker.
    3. Queues a job in Redis for the 'synced_files' collection.
    4. Logs the file in 'processed_files_log' to prevent duplicate ingestion by the nightly cron job.

    Args:
        kb_id (None | str | Unset): Optional knowledge base ID. If omitted, uses the caller's
            personal knowledge base.
        body (BodyIngestFileAsyncV1IngestionFileAsyncPost):

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

    kwargs = _get_kwargs(
        body=body,
        kb_id=kb_id,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    *,
    client: AuthenticatedClient,
    body: BodyIngestFileAsyncV1IngestionFileAsyncPost,
    kb_id: None | str | Unset = UNSET,
) -> HTTPValidationError | IngestAsyncResponse | None:
    """Ingest File Async

     [V2] Accepts a file for high-priority ingestion into the user's permanent knowledge base.
    1. Persists the file to the user's permanent S3 folder (e.g., files/<user_id>/).
    2. Stages a copy for the ingestion worker.
    3. Queues a job in Redis for the 'synced_files' collection.
    4. Logs the file in 'processed_files_log' to prevent duplicate ingestion by the nightly cron job.

    Args:
        kb_id (None | str | Unset): Optional knowledge base ID. If omitted, uses the caller's
            personal knowledge base.
        body (BodyIngestFileAsyncV1IngestionFileAsyncPost):

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

    return (
        await asyncio_detailed(
            client=client,
            body=body,
            kb_id=kb_id,
        )
    ).parsed
