from http import HTTPStatus
from typing import Any, Optional, Union, cast
from uuid import UUID

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.upload_description import UploadDescription
from ...models.upload_request import UploadRequest
from ...types import Response


def _get_kwargs(
    user_context: UUID,
    *,
    body: UploadRequest,
) -> dict[str, Any]:
    headers: dict[str, Any] = {}

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": f"/file-manager/v1/{user_context}/files",
    }

    _body = body.to_dict()

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

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[Union[Any, UploadDescription]]:
    if response.status_code == 201:
        response_201 = UploadDescription.from_dict(response.json())

        return response_201
    if response.status_code == 400:
        response_400 = cast(Any, None)
        return response_400
    if response.status_code == 401:
        response_401 = cast(Any, None)
        return response_401
    if response.status_code == 403:
        response_403 = cast(Any, None)
        return response_403
    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


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


def sync_detailed(
    user_context: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: UploadRequest,
) -> Response[Union[Any, UploadDescription]]:
    """Register a file to be uploaded

     Register a new File for upload.

    Args:
        user_context (UUID):  Example: 7df13462-54d8-4fd7-a2e8-5e18754d4030.
        body (UploadRequest): File Upload Request

    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[Union[Any, UploadDescription]]
    """

    kwargs = _get_kwargs(
        user_context=user_context,
        body=body,
    )

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

    return _build_response(client=client, response=response)


def sync(
    user_context: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: UploadRequest,
) -> Optional[Union[Any, UploadDescription]]:
    """Register a file to be uploaded

     Register a new File for upload.

    Args:
        user_context (UUID):  Example: 7df13462-54d8-4fd7-a2e8-5e18754d4030.
        body (UploadRequest): File Upload Request

    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:
        Union[Any, UploadDescription]
    """

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


async def asyncio_detailed(
    user_context: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: UploadRequest,
) -> Response[Union[Any, UploadDescription]]:
    """Register a file to be uploaded

     Register a new File for upload.

    Args:
        user_context (UUID):  Example: 7df13462-54d8-4fd7-a2e8-5e18754d4030.
        body (UploadRequest): File Upload Request

    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[Union[Any, UploadDescription]]
    """

    kwargs = _get_kwargs(
        user_context=user_context,
        body=body,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    user_context: UUID,
    *,
    client: Union[AuthenticatedClient, Client],
    body: UploadRequest,
) -> Optional[Union[Any, UploadDescription]]:
    """Register a file to be uploaded

     Register a new File for upload.

    Args:
        user_context (UUID):  Example: 7df13462-54d8-4fd7-a2e8-5e18754d4030.
        body (UploadRequest): File Upload Request

    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:
        Union[Any, UploadDescription]
    """

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