from http import HTTPStatus
from typing import Any, cast
from urllib.parse import quote

import httpx

from ...client import AuthenticatedClient, Client
from ...types import Response, UNSET
from ... import errors

from ...models.context import Context
from ...models.context_update import ContextUpdate
from ...models.not_found_error_response import NotFoundErrorResponse
from ...models.validation_error_response import ValidationErrorResponse
from typing import cast



def _get_kwargs(
    id: str,
    *,
    body: ContextUpdate,

) -> dict[str, Any]:
    headers: dict[str, Any] = {}


    

    

    _kwargs: dict[str, Any] = {
        "method": "patch",
        "url": "/api/v1/contexts/{id}".format(id=quote(str(id), safe=""),),
    }

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

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

    _kwargs["headers"] = headers
    return _kwargs



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



        return response_200

    def _parse_response_default(data: object) -> NotFoundErrorResponse | ValidationErrorResponse:
        try:
            if not isinstance(data, dict):
                raise TypeError()
            response_default_type_0 = NotFoundErrorResponse.from_dict(data)



            return response_default_type_0
        except (TypeError, ValueError, AttributeError, KeyError):
            pass
        if not isinstance(data, dict):
            raise TypeError()
        response_default_type_1 = ValidationErrorResponse.from_dict(data)



        return response_default_type_1

    response_default = _parse_response_default(response.json())

    return response_default



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


def sync_detailed(
    id: str,
    *,
    client: AuthenticatedClient | Client,
    body: ContextUpdate,

) -> Response[Context | NotFoundErrorResponse | ValidationErrorResponse]:
    """ Update a context's renderer

     Update the context-level renderer default. The `id` and `sources` fields are not writable via PATCH.

    Args:
        id (str):
        body (ContextUpdate): Request body for updating a context's renderer default. Example:
            {'renderer': {'md_engine': 'python-markdown', 'hl_engine': 'none'}}.

    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[Context | NotFoundErrorResponse | ValidationErrorResponse]
     """


    kwargs = _get_kwargs(
        id=id,
body=body,

    )

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

    return _build_response(client=client, response=response)

def sync(
    id: str,
    *,
    client: AuthenticatedClient | Client,
    body: ContextUpdate,

) -> Context | NotFoundErrorResponse | ValidationErrorResponse | None:
    """ Update a context's renderer

     Update the context-level renderer default. The `id` and `sources` fields are not writable via PATCH.

    Args:
        id (str):
        body (ContextUpdate): Request body for updating a context's renderer default. Example:
            {'renderer': {'md_engine': 'python-markdown', 'hl_engine': 'none'}}.

    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:
        Context | NotFoundErrorResponse | ValidationErrorResponse
     """


    return sync_detailed(
        id=id,
client=client,
body=body,

    ).parsed

async def asyncio_detailed(
    id: str,
    *,
    client: AuthenticatedClient | Client,
    body: ContextUpdate,

) -> Response[Context | NotFoundErrorResponse | ValidationErrorResponse]:
    """ Update a context's renderer

     Update the context-level renderer default. The `id` and `sources` fields are not writable via PATCH.

    Args:
        id (str):
        body (ContextUpdate): Request body for updating a context's renderer default. Example:
            {'renderer': {'md_engine': 'python-markdown', 'hl_engine': 'none'}}.

    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[Context | NotFoundErrorResponse | ValidationErrorResponse]
     """


    kwargs = _get_kwargs(
        id=id,
body=body,

    )

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

    return _build_response(client=client, response=response)

async def asyncio(
    id: str,
    *,
    client: AuthenticatedClient | Client,
    body: ContextUpdate,

) -> Context | NotFoundErrorResponse | ValidationErrorResponse | None:
    """ Update a context's renderer

     Update the context-level renderer default. The `id` and `sources` fields are not writable via PATCH.

    Args:
        id (str):
        body (ContextUpdate): Request body for updating a context's renderer default. Example:
            {'renderer': {'md_engine': 'python-markdown', 'hl_engine': 'none'}}.

    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:
        Context | NotFoundErrorResponse | ValidationErrorResponse
     """


    return (await asyncio_detailed(
        id=id,
client=client,
body=body,

    )).parsed
