"""
This file is generated by the openapi-python-client tool via the generate_api_client.py script

It is a customized template from the openapi-python-client tool's default template:
https://github.com/openapi-generators/openapi-python-client/blob/861ef5622f10fc96d240dc9becb0edf94e61446c/openapi_python_client/templates/endpoint_module.py.jinja

The main changes are:
- Update the API call responses to either return the successful response type or raise an error by:
    - Updating the _parse_response function to raise an error if the response status code is not in the 2xx range
- Inject a client into every method via a context manager
"""

from http import HTTPStatus
from typing import Any, Dict, List, Union

import httpx

from ...client import _client_context
from ...errors import get_error_for_response
from ...models.labeled_memory import LabeledMemory
from ...models.labeled_memory_update import LabeledMemoryUpdate
from ...models.scored_memory import ScoredMemory
from ...models.scored_memory_update import ScoredMemoryUpdate
from ...types import Response


def _get_kwargs(
    name_or_id: str,
    *,
    body: Union[List["LabeledMemoryUpdate"], List["ScoredMemoryUpdate"]],
) -> dict[str, Any]:
    headers: Dict[str, Any] = {}

    _kwargs: dict[str, Any] = {
        "method": "patch",
        "url": f"/gpu/memoryset/{name_or_id}/memories",
    }

    _body: List[Dict[str, Any]]
    if isinstance(body, list):
        _body = []
        for body_type_0_item_data in body:
            body_type_0_item = body_type_0_item_data.to_dict()
            _body.append(body_type_0_item)

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

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(*, response: httpx.Response) -> Union[List["LabeledMemory"], List["ScoredMemory"]]:
    if response.status_code == 200:

        def _parse_response_200(data: object) -> Union[List["LabeledMemory"], List["ScoredMemory"]]:
            try:
                if not isinstance(data, list):
                    raise TypeError()
                response_200_type_0 = []
                _response_200_type_0 = data
                for response_200_type_0_item_data in _response_200_type_0:
                    response_200_type_0_item = LabeledMemory.from_dict(response_200_type_0_item_data)

                    response_200_type_0.append(response_200_type_0_item)

                return response_200_type_0
            except:  # noqa: E722
                pass
            if not isinstance(data, list):
                raise TypeError()
            response_200_type_1 = []
            _response_200_type_1 = data
            for response_200_type_1_item_data in _response_200_type_1:
                response_200_type_1_item = ScoredMemory.from_dict(response_200_type_1_item_data)

                response_200_type_1.append(response_200_type_1_item)

            return response_200_type_1

        response_200 = _parse_response_200(response.json())

        return response_200
    if response.status_code == 401:
        raise get_error_for_response(response)
    if response.status_code == 500:
        raise get_error_for_response(response)
    if response.status_code == 503:
        raise get_error_for_response(response)
    if response.status_code == 404:
        raise get_error_for_response(response)
    else:
        raise get_error_for_response(response)


def _build_response(*, response: httpx.Response) -> Response[Union[List["LabeledMemory"], List["ScoredMemory"]]]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(response=response),
    )


def sync_detailed(
    name_or_id: str,
    *,
    body: Union[List["LabeledMemoryUpdate"], List["ScoredMemoryUpdate"]],
) -> Response[Union[List["LabeledMemory"], List["ScoredMemory"]]]:
    """Update Memories

    Args:
        name_or_id (str):
        body (Union[List['LabeledMemoryUpdate'], List['ScoredMemoryUpdate']]):

    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[List['LabeledMemory'], List['ScoredMemory']]]
    """

    kwargs = _get_kwargs(
        name_or_id=name_or_id,
        body=body,
    )

    with _client_context() as client:
        response = client.get_httpx_client().request(
            **kwargs,
        )

        return _build_response(response=response)


def sync(
    name_or_id: str,
    *,
    body: Union[List["LabeledMemoryUpdate"], List["ScoredMemoryUpdate"]],
) -> Union[List["LabeledMemory"], List["ScoredMemory"]]:
    """Update Memories

    Args:
        name_or_id (str):
        body (Union[List['LabeledMemoryUpdate'], List['ScoredMemoryUpdate']]):

    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[List['LabeledMemory'], List['ScoredMemory']]
    """

    return sync_detailed(
        name_or_id=name_or_id,
        body=body,
    ).parsed


async def asyncio_detailed(
    name_or_id: str,
    *,
    body: Union[List["LabeledMemoryUpdate"], List["ScoredMemoryUpdate"]],
) -> Response[Union[List["LabeledMemory"], List["ScoredMemory"]]]:
    """Update Memories

    Args:
        name_or_id (str):
        body (Union[List['LabeledMemoryUpdate'], List['ScoredMemoryUpdate']]):

    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[List['LabeledMemory'], List['ScoredMemory']]]
    """

    kwargs = _get_kwargs(
        name_or_id=name_or_id,
        body=body,
    )

    with _client_context() as client:
        response = await client.get_async_httpx_client().request(**kwargs)

    return _build_response(response=response)


async def asyncio(
    name_or_id: str,
    *,
    body: Union[List["LabeledMemoryUpdate"], List["ScoredMemoryUpdate"]],
) -> Union[List["LabeledMemory"], List["ScoredMemory"]]:
    """Update Memories

    Args:
        name_or_id (str):
        body (Union[List['LabeledMemoryUpdate'], List['ScoredMemoryUpdate']]):

    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[List['LabeledMemory'], List['ScoredMemory']]
    """

    return (
        await asyncio_detailed(
            name_or_id=name_or_id,
            body=body,
        )
    ).parsed
