# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.unchecked_base_model import construct_type
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.group import Group
from ..types.http_validation_error import HttpValidationError
from ..types.manager_type import ManagerType
from .types.group_create_manager_config import GroupCreateManagerConfig
from .types.group_update_manager_config import GroupUpdateManagerConfig
from .types.groups_list_request_order import GroupsListRequestOrder

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawGroupsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def list(
        self,
        *,
        manager_type: typing.Optional[ManagerType] = None,
        before: typing.Optional[str] = None,
        after: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        order: typing.Optional[GroupsListRequestOrder] = None,
        order_by: typing.Optional[typing.Literal["created_at"]] = None,
        project_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[Group]]:
        """
        Fetch all multi-agent groups matching query.

        Parameters
        ----------
        manager_type : typing.Optional[ManagerType]
            Search groups by manager type

        before : typing.Optional[str]
            Group ID cursor for pagination. Returns groups that come before this group ID in the specified sort order

        after : typing.Optional[str]
            Group ID cursor for pagination. Returns groups that come after this group ID in the specified sort order

        limit : typing.Optional[int]
            Maximum number of groups to return

        order : typing.Optional[GroupsListRequestOrder]
            Sort order for groups by creation time. 'asc' for oldest first, 'desc' for newest first

        order_by : typing.Optional[typing.Literal["created_at"]]
            Field to sort by

        project_id : typing.Optional[str]
            Search groups by project id

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.List[Group]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/groups/",
            method="GET",
            params={
                "manager_type": manager_type,
                "before": before,
                "after": after,
                "limit": limit,
                "order": order,
                "order_by": order_by,
                "project_id": project_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[Group],
                    construct_type(
                        type_=typing.List[Group],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create(
        self,
        *,
        agent_ids: typing.Sequence[str],
        description: str,
        manager_config: typing.Optional[GroupCreateManagerConfig] = OMIT,
        project_id: typing.Optional[str] = OMIT,
        shared_block_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        hidden: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Group]:
        """
        Create a new multi-agent group with the specified configuration.

        Parameters
        ----------
        agent_ids : typing.Sequence[str]


        description : str


        manager_config : typing.Optional[GroupCreateManagerConfig]


        project_id : typing.Optional[str]
            The associated project id.

        shared_block_ids : typing.Optional[typing.Sequence[str]]


        hidden : typing.Optional[bool]
            If set to True, the group will be hidden.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[Group]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/groups/",
            method="POST",
            json={
                "agent_ids": agent_ids,
                "description": description,
                "manager_config": convert_and_respect_annotation_metadata(
                    object_=manager_config, annotation=GroupCreateManagerConfig, direction="write"
                ),
                "project_id": project_id,
                "shared_block_ids": shared_block_ids,
                "hidden": hidden,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Group,
                    construct_type(
                        type_=Group,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def count(self, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[int]:
        """
        Get the count of all groups associated with a given user.

        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[int]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/groups/count",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    int,
                    construct_type(
                        type_=int,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def retrieve(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[Group]:
        """
        Retrieve the group by id.

        Parameters
        ----------
        group_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[Group]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/groups/{jsonable_encoder(group_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Group,
                    construct_type(
                        type_=Group,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.Optional[typing.Any]]:
        """
        Delete a multi-agent group.

        Parameters
        ----------
        group_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Optional[typing.Any]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/groups/{jsonable_encoder(group_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[typing.Any],
                    construct_type(
                        type_=typing.Optional[typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def modify(
        self,
        group_id: str,
        *,
        agent_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        description: typing.Optional[str] = OMIT,
        manager_config: typing.Optional[GroupUpdateManagerConfig] = OMIT,
        project_id: typing.Optional[str] = OMIT,
        shared_block_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Group]:
        """
        Create a new multi-agent group with the specified configuration.

        Parameters
        ----------
        group_id : str

        agent_ids : typing.Optional[typing.Sequence[str]]


        description : typing.Optional[str]


        manager_config : typing.Optional[GroupUpdateManagerConfig]


        project_id : typing.Optional[str]
            The associated project id.

        shared_block_ids : typing.Optional[typing.Sequence[str]]


        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[Group]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/groups/{jsonable_encoder(group_id)}",
            method="PATCH",
            json={
                "agent_ids": agent_ids,
                "description": description,
                "manager_config": convert_and_respect_annotation_metadata(
                    object_=manager_config, annotation=GroupUpdateManagerConfig, direction="write"
                ),
                "project_id": project_id,
                "shared_block_ids": shared_block_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Group,
                    construct_type(
                        type_=Group,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawGroupsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        manager_type: typing.Optional[ManagerType] = None,
        before: typing.Optional[str] = None,
        after: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        order: typing.Optional[GroupsListRequestOrder] = None,
        order_by: typing.Optional[typing.Literal["created_at"]] = None,
        project_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[Group]]:
        """
        Fetch all multi-agent groups matching query.

        Parameters
        ----------
        manager_type : typing.Optional[ManagerType]
            Search groups by manager type

        before : typing.Optional[str]
            Group ID cursor for pagination. Returns groups that come before this group ID in the specified sort order

        after : typing.Optional[str]
            Group ID cursor for pagination. Returns groups that come after this group ID in the specified sort order

        limit : typing.Optional[int]
            Maximum number of groups to return

        order : typing.Optional[GroupsListRequestOrder]
            Sort order for groups by creation time. 'asc' for oldest first, 'desc' for newest first

        order_by : typing.Optional[typing.Literal["created_at"]]
            Field to sort by

        project_id : typing.Optional[str]
            Search groups by project id

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.List[Group]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/groups/",
            method="GET",
            params={
                "manager_type": manager_type,
                "before": before,
                "after": after,
                "limit": limit,
                "order": order,
                "order_by": order_by,
                "project_id": project_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[Group],
                    construct_type(
                        type_=typing.List[Group],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create(
        self,
        *,
        agent_ids: typing.Sequence[str],
        description: str,
        manager_config: typing.Optional[GroupCreateManagerConfig] = OMIT,
        project_id: typing.Optional[str] = OMIT,
        shared_block_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        hidden: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Group]:
        """
        Create a new multi-agent group with the specified configuration.

        Parameters
        ----------
        agent_ids : typing.Sequence[str]


        description : str


        manager_config : typing.Optional[GroupCreateManagerConfig]


        project_id : typing.Optional[str]
            The associated project id.

        shared_block_ids : typing.Optional[typing.Sequence[str]]


        hidden : typing.Optional[bool]
            If set to True, the group will be hidden.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[Group]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/groups/",
            method="POST",
            json={
                "agent_ids": agent_ids,
                "description": description,
                "manager_config": convert_and_respect_annotation_metadata(
                    object_=manager_config, annotation=GroupCreateManagerConfig, direction="write"
                ),
                "project_id": project_id,
                "shared_block_ids": shared_block_ids,
                "hidden": hidden,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Group,
                    construct_type(
                        type_=Group,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def count(self, *, request_options: typing.Optional[RequestOptions] = None) -> AsyncHttpResponse[int]:
        """
        Get the count of all groups associated with a given user.

        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[int]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/groups/count",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    int,
                    construct_type(
                        type_=int,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def retrieve(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Group]:
        """
        Retrieve the group by id.

        Parameters
        ----------
        group_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[Group]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/groups/{jsonable_encoder(group_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Group,
                    construct_type(
                        type_=Group,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self, group_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.Optional[typing.Any]]:
        """
        Delete a multi-agent group.

        Parameters
        ----------
        group_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Optional[typing.Any]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/groups/{jsonable_encoder(group_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[typing.Any],
                    construct_type(
                        type_=typing.Optional[typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def modify(
        self,
        group_id: str,
        *,
        agent_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        description: typing.Optional[str] = OMIT,
        manager_config: typing.Optional[GroupUpdateManagerConfig] = OMIT,
        project_id: typing.Optional[str] = OMIT,
        shared_block_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Group]:
        """
        Create a new multi-agent group with the specified configuration.

        Parameters
        ----------
        group_id : str

        agent_ids : typing.Optional[typing.Sequence[str]]


        description : typing.Optional[str]


        manager_config : typing.Optional[GroupUpdateManagerConfig]


        project_id : typing.Optional[str]
            The associated project id.

        shared_block_ids : typing.Optional[typing.Sequence[str]]


        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[Group]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/groups/{jsonable_encoder(group_id)}",
            method="PATCH",
            json={
                "agent_ids": agent_ids,
                "description": description,
                "manager_config": convert_and_respect_annotation_metadata(
                    object_=manager_config, annotation=GroupUpdateManagerConfig, direction="write"
                ),
                "project_id": project_id,
                "shared_block_ids": shared_block_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Group,
                    construct_type(
                        type_=Group,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
