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.not_found_error_response import NotFoundErrorResponse
from ...models.source import Source
from ...models.source_create import SourceCreate
from ...models.validation_error_response import ValidationErrorResponse
from typing import cast



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

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


    

    

    _kwargs: dict[str, Any] = {
        "method": "post",
        "url": "/api/v1/contexts/{id}/sources".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) -> ConflictErrorResponse | NotFoundErrorResponse | ValidationErrorResponse | Source:
    if response.status_code == 201:
        response_201 = Source.from_dict(response.json())



        return response_201

    def _parse_response_default(data: object) -> ConflictErrorResponse | 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
        try:
            if not isinstance(data, dict):
                raise TypeError()
            response_default_type_1 = ValidationErrorResponse.from_dict(data)



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



        return response_default_type_2

    response_default = _parse_response_default(response.json())

    return response_default



def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[ConflictErrorResponse | NotFoundErrorResponse | ValidationErrorResponse | Source]:
    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: SourceCreate,

) -> Response[ConflictErrorResponse | NotFoundErrorResponse | ValidationErrorResponse | Source]:
    """ Add a source to a context

     Add a source to a context. The server derives `slug` and rejects 409 if it collides.

    Args:
        id (str):
        body (SourceCreate): Request body for adding a source to a context. Example: {'transport':
            'ssh', 'location': 'hostA:/path/to/docs', 'alias': 'hostA-docs'}.

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


    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: SourceCreate,

) -> ConflictErrorResponse | NotFoundErrorResponse | ValidationErrorResponse | Source | None:
    """ Add a source to a context

     Add a source to a context. The server derives `slug` and rejects 409 if it collides.

    Args:
        id (str):
        body (SourceCreate): Request body for adding a source to a context. Example: {'transport':
            'ssh', 'location': 'hostA:/path/to/docs', 'alias': 'hostA-docs'}.

    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 | NotFoundErrorResponse | ValidationErrorResponse | Source
     """


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

    ).parsed

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

) -> Response[ConflictErrorResponse | NotFoundErrorResponse | ValidationErrorResponse | Source]:
    """ Add a source to a context

     Add a source to a context. The server derives `slug` and rejects 409 if it collides.

    Args:
        id (str):
        body (SourceCreate): Request body for adding a source to a context. Example: {'transport':
            'ssh', 'location': 'hostA:/path/to/docs', 'alias': 'hostA-docs'}.

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


    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: SourceCreate,

) -> ConflictErrorResponse | NotFoundErrorResponse | ValidationErrorResponse | Source | None:
    """ Add a source to a context

     Add a source to a context. The server derives `slug` and rejects 409 if it collides.

    Args:
        id (str):
        body (SourceCreate): Request body for adding a source to a context. Example: {'transport':
            'ssh', 'location': 'hostA:/path/to/docs', 'alias': 'hostA-docs'}.

    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 | NotFoundErrorResponse | ValidationErrorResponse | Source
     """


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

    )).parsed
