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

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.conversation_response import ConversationResponse
from ...models.http_validation_error import HTTPValidationError
from ...types import Response, Unset


def _get_kwargs(
    workspace_ext_id: str,
    *,
    workspace_key: str | Unset = "",
) -> dict[str, Any]:
    headers: dict[str, Any] = {}
    if not isinstance(workspace_key, Unset):
        headers["workspace-key"] = workspace_key

    _kwargs: dict[str, Any] = {
        "method": "get",
        "url": "/api/workspace/{workspace_ext_id}/conversations".format(
            workspace_ext_id=quote(str(workspace_ext_id), safe=""),
        ),
    }

    _kwargs["headers"] = headers
    return _kwargs


def _parse_response(
    *, client: AuthenticatedClient | Client, response: httpx.Response
) -> HTTPValidationError | list[ConversationResponse] | None:
    if response.status_code == 200:
        response_200 = []
        _response_200 = response.json()
        for response_200_item_data in _response_200:
            response_200_item = ConversationResponse.from_dict(response_200_item_data)

            response_200.append(response_200_item)

        return response_200

    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())

        return response_422

    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


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


def sync_detailed(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    workspace_key: str | Unset = "",
) -> Response[HTTPValidationError | list[ConversationResponse]]:
    """Get User Workspace Conversations

     Retrieve conversations for a workspace where the current user is:
    - The creator of the conversation, or
    - Listed in the ConvoUsers table.

    Return conversation metadata including:
    - External ID
    - Title
    - Last updated date
    - Number of messages
    - Whether the current user is the creator

    Args:
        workspace_ext_id (str):
        workspace_key (str | Unset):  Default: ''.

    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[HTTPValidationError | list[ConversationResponse]]
    """

    kwargs = _get_kwargs(
        workspace_ext_id=workspace_ext_id,
        workspace_key=workspace_key,
    )

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

    return _build_response(client=client, response=response)


def sync(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    workspace_key: str | Unset = "",
) -> HTTPValidationError | list[ConversationResponse] | None:
    """Get User Workspace Conversations

     Retrieve conversations for a workspace where the current user is:
    - The creator of the conversation, or
    - Listed in the ConvoUsers table.

    Return conversation metadata including:
    - External ID
    - Title
    - Last updated date
    - Number of messages
    - Whether the current user is the creator

    Args:
        workspace_ext_id (str):
        workspace_key (str | Unset):  Default: ''.

    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:
        HTTPValidationError | list[ConversationResponse]
    """

    return sync_detailed(
        workspace_ext_id=workspace_ext_id,
        client=client,
        workspace_key=workspace_key,
    ).parsed


async def asyncio_detailed(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    workspace_key: str | Unset = "",
) -> Response[HTTPValidationError | list[ConversationResponse]]:
    """Get User Workspace Conversations

     Retrieve conversations for a workspace where the current user is:
    - The creator of the conversation, or
    - Listed in the ConvoUsers table.

    Return conversation metadata including:
    - External ID
    - Title
    - Last updated date
    - Number of messages
    - Whether the current user is the creator

    Args:
        workspace_ext_id (str):
        workspace_key (str | Unset):  Default: ''.

    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[HTTPValidationError | list[ConversationResponse]]
    """

    kwargs = _get_kwargs(
        workspace_ext_id=workspace_ext_id,
        workspace_key=workspace_key,
    )

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

    return _build_response(client=client, response=response)


async def asyncio(
    workspace_ext_id: str,
    *,
    client: AuthenticatedClient | Client,
    workspace_key: str | Unset = "",
) -> HTTPValidationError | list[ConversationResponse] | None:
    """Get User Workspace Conversations

     Retrieve conversations for a workspace where the current user is:
    - The creator of the conversation, or
    - Listed in the ConvoUsers table.

    Return conversation metadata including:
    - External ID
    - Title
    - Last updated date
    - Number of messages
    - Whether the current user is the creator

    Args:
        workspace_ext_id (str):
        workspace_key (str | Unset):  Default: ''.

    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:
        HTTPValidationError | list[ConversationResponse]
    """

    return (
        await asyncio_detailed(
            workspace_ext_id=workspace_ext_id,
            client=client,
            workspace_key=workspace_key,
        )
    ).parsed
