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.conflict_error_response import ConflictErrorResponse
from ...models.context import Context
from ...models.context_create import ContextCreate
from ...models.validation_error_response import ValidationErrorResponse
from typing import cast



def _get_kwargs(
    *,
    body: ContextCreate,

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


    

    

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/api/v1/contexts/",
    }

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

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

    _kwargs["headers"] = headers
    return _kwargs



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



        return response_201

    def _parse_response_default(data: object) -> ConflictErrorResponse | ValidationErrorResponse:
        try:
            if not isinstance(data, dict):
                raise TypeError()
            response_default_type_0 = ValidationErrorResponse.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 = ConflictErrorResponse.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[ConflictErrorResponse | ValidationErrorResponse | Context]:
    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: ContextCreate,

) -> Response[ConflictErrorResponse | ValidationErrorResponse | Context]:
    """ Create a context

     Create a new context with an optional renderer default and initial sources.

    Args:
        body (ContextCreate): Request body for creating a context. Example: {'id': 'project-docs',
            'sources': [{'transport': 'local', 'location': '/path/to/project-docs', 'alias': 'project-
            docs'}], 'renderer': {'md_engine': 'pandoc'}}.

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


    kwargs = _get_kwargs(
        body=body,

    )

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

    return _build_response(client=client, response=response)

def sync(
    *,
    client: AuthenticatedClient | Client,
    body: ContextCreate,

) -> ConflictErrorResponse | ValidationErrorResponse | Context | None:
    """ Create a context

     Create a new context with an optional renderer default and initial sources.

    Args:
        body (ContextCreate): Request body for creating a context. Example: {'id': 'project-docs',
            'sources': [{'transport': 'local', 'location': '/path/to/project-docs', 'alias': 'project-
            docs'}], 'renderer': {'md_engine': 'pandoc'}}.

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


    return sync_detailed(
        client=client,
body=body,

    ).parsed

async def asyncio_detailed(
    *,
    client: AuthenticatedClient | Client,
    body: ContextCreate,

) -> Response[ConflictErrorResponse | ValidationErrorResponse | Context]:
    """ Create a context

     Create a new context with an optional renderer default and initial sources.

    Args:
        body (ContextCreate): Request body for creating a context. Example: {'id': 'project-docs',
            'sources': [{'transport': 'local', 'location': '/path/to/project-docs', 'alias': 'project-
            docs'}], 'renderer': {'md_engine': 'pandoc'}}.

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


    kwargs = _get_kwargs(
        body=body,

    )

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

    return _build_response(client=client, response=response)

async def asyncio(
    *,
    client: AuthenticatedClient | Client,
    body: ContextCreate,

) -> ConflictErrorResponse | ValidationErrorResponse | Context | None:
    """ Create a context

     Create a new context with an optional renderer default and initial sources.

    Args:
        body (ContextCreate): Request body for creating a context. Example: {'id': 'project-docs',
            'sources': [{'transport': 'local', 'location': '/path/to/project-docs', 'alias': 'project-
            docs'}], 'renderer': {'md_engine': 'pandoc'}}.

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


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

    )).parsed
