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

import typing
from ..core.client_wrapper import SyncClientWrapper
from ..core.request_options import RequestOptions
from ..types.agent import Agent
from ..core.pydantic_utilities import parse_obj_as
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..types.composition_mode_dto import CompositionModeDto
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..core.jsonable_encoder import jsonable_encoder
from ..errors.not_found_error import NotFoundError
from ..types.agent_tag_update_params import AgentTagUpdateParams
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.client_wrapper import AsyncClientWrapper

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


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

    def list(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[Agent]:
        """
        Retrieves a list of all agents in the system.

        Returns an empty list if no agents exist.
        Agents are returned in no guaranteed order.

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

        Returns
        -------
        typing.List[Agent]
            List of all agents in the system

        Examples
        --------
        from parlant.client import ParlantClient

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.agents.list()
        """
        _response = self._client_wrapper.httpx_client.request(
            "agents",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Agent],
                    parse_obj_as(
                        type_=typing.List[Agent],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self,
        *,
        name: str,
        description: typing.Optional[str] = OMIT,
        max_engine_iterations: typing.Optional[int] = OMIT,
        composition_mode: typing.Optional[CompositionModeDto] = OMIT,
        tags: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Agent:
        """
        Creates a new agent in the system.

        The agent will be initialized with the provided name and optional settings.
        A unique identifier will be automatically generated.

        Default behaviors:
        - `name` defaults to `"Unnamed Agent"` if not provided
        - `description` defaults to `None`
        - `max_engine_iterations` defaults to `None` (uses system default)

        Parameters
        ----------
        name : str
            The display name of the agent, mainly for management purposes

        description : typing.Optional[str]
            Detailed description of the agent's purpose and capabilities

        max_engine_iterations : typing.Optional[int]
            Maximum number of processing iterations the agent can perform per request

        composition_mode : typing.Optional[CompositionModeDto]

        tags : typing.Optional[typing.Sequence[str]]
            List of tag IDs associated with the agent

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

        Returns
        -------
        Agent
            Agent successfully created. Returns the complete agent object including generated ID.

        Examples
        --------
        from parlant.client import ParlantClient

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.agents.create(
            name="Haxon",
            description="Technical Support Assistant",
            max_engine_iterations=3,
            composition_mode="fluid",
            tags=["tag1", "tag2"],
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "agents",
            method="POST",
            json={
                "name": name,
                "description": description,
                "max_engine_iterations": max_engine_iterations,
                "composition_mode": composition_mode,
                "tags": tags,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Agent,
                    parse_obj_as(
                        type_=Agent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def retrieve(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> Agent:
        """
        Retrieves details of a specific agent by ID.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent

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

        Returns
        -------
        Agent
            Agent details successfully retrieved. Returns the complete agent object.

        Examples
        --------
        from parlant.client import ParlantClient

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.agents.retrieve(
            agent_id="IUCGT-lvpS",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Agent,
                    parse_obj_as(
                        type_=Agent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def delete(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> None:
        """
        Deletes an agent from the agent.

        Deleting a non-existent agent will return 404.
        No content will be returned from a successful deletion.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent

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

        Returns
        -------
        None

        Examples
        --------
        from parlant.client import ParlantClient

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.agents.delete(
            agent_id="IUCGT-lvpS",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update(
        self,
        agent_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        max_engine_iterations: typing.Optional[int] = OMIT,
        composition_mode: typing.Optional[CompositionModeDto] = OMIT,
        tags: typing.Optional[AgentTagUpdateParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Agent:
        """
        Updates an existing agent's attributes.

        Only the provided attributes will be updated; others will remain unchanged.
        The agent's ID and creation timestamp cannot be modified.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent

        name : typing.Optional[str]
            The display name of the agent, mainly for management purposes

        description : typing.Optional[str]
            Detailed description of the agent's purpose and capabilities

        max_engine_iterations : typing.Optional[int]
            Maximum number of processing iterations the agent can perform per request

        composition_mode : typing.Optional[CompositionModeDto]

        tags : typing.Optional[AgentTagUpdateParams]

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

        Returns
        -------
        Agent
            Agent successfully updated. Returns the updated agent.

        Examples
        --------
        from parlant.client import ParlantClient

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.agents.update(
            agent_id="IUCGT-lvpS",
            name="Haxon",
            description="Technical Support Assistant",
            max_engine_iterations=3,
            composition_mode="fluid",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "max_engine_iterations": max_engine_iterations,
                "composition_mode": composition_mode,
                "tags": convert_and_respect_annotation_metadata(
                    object_=tags, annotation=AgentTagUpdateParams, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Agent,
                    parse_obj_as(
                        type_=Agent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def list(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> typing.List[Agent]:
        """
        Retrieves a list of all agents in the system.

        Returns an empty list if no agents exist.
        Agents are returned in no guaranteed order.

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

        Returns
        -------
        typing.List[Agent]
            List of all agents in the system

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

        client = AsyncParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.agents.list()


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "agents",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Agent],
                    parse_obj_as(
                        type_=typing.List[Agent],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self,
        *,
        name: str,
        description: typing.Optional[str] = OMIT,
        max_engine_iterations: typing.Optional[int] = OMIT,
        composition_mode: typing.Optional[CompositionModeDto] = OMIT,
        tags: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Agent:
        """
        Creates a new agent in the system.

        The agent will be initialized with the provided name and optional settings.
        A unique identifier will be automatically generated.

        Default behaviors:
        - `name` defaults to `"Unnamed Agent"` if not provided
        - `description` defaults to `None`
        - `max_engine_iterations` defaults to `None` (uses system default)

        Parameters
        ----------
        name : str
            The display name of the agent, mainly for management purposes

        description : typing.Optional[str]
            Detailed description of the agent's purpose and capabilities

        max_engine_iterations : typing.Optional[int]
            Maximum number of processing iterations the agent can perform per request

        composition_mode : typing.Optional[CompositionModeDto]

        tags : typing.Optional[typing.Sequence[str]]
            List of tag IDs associated with the agent

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

        Returns
        -------
        Agent
            Agent successfully created. Returns the complete agent object including generated ID.

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

        client = AsyncParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.agents.create(
                name="Haxon",
                description="Technical Support Assistant",
                max_engine_iterations=3,
                composition_mode="fluid",
                tags=["tag1", "tag2"],
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "agents",
            method="POST",
            json={
                "name": name,
                "description": description,
                "max_engine_iterations": max_engine_iterations,
                "composition_mode": composition_mode,
                "tags": tags,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Agent,
                    parse_obj_as(
                        type_=Agent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def retrieve(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> Agent:
        """
        Retrieves details of a specific agent by ID.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent

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

        Returns
        -------
        Agent
            Agent details successfully retrieved. Returns the complete agent object.

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

        client = AsyncParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.agents.retrieve(
                agent_id="IUCGT-lvpS",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Agent,
                    parse_obj_as(
                        type_=Agent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def delete(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> None:
        """
        Deletes an agent from the agent.

        Deleting a non-existent agent will return 404.
        No content will be returned from a successful deletion.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent

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

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

        client = AsyncParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.agents.delete(
                agent_id="IUCGT-lvpS",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update(
        self,
        agent_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        max_engine_iterations: typing.Optional[int] = OMIT,
        composition_mode: typing.Optional[CompositionModeDto] = OMIT,
        tags: typing.Optional[AgentTagUpdateParams] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Agent:
        """
        Updates an existing agent's attributes.

        Only the provided attributes will be updated; others will remain unchanged.
        The agent's ID and creation timestamp cannot be modified.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent

        name : typing.Optional[str]
            The display name of the agent, mainly for management purposes

        description : typing.Optional[str]
            Detailed description of the agent's purpose and capabilities

        max_engine_iterations : typing.Optional[int]
            Maximum number of processing iterations the agent can perform per request

        composition_mode : typing.Optional[CompositionModeDto]

        tags : typing.Optional[AgentTagUpdateParams]

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

        Returns
        -------
        Agent
            Agent successfully updated. Returns the updated agent.

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

        client = AsyncParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.agents.update(
                agent_id="IUCGT-lvpS",
                name="Haxon",
                description="Technical Support Assistant",
                max_engine_iterations=3,
                composition_mode="fluid",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="PATCH",
            json={
                "name": name,
                "description": description,
                "max_engine_iterations": max_engine_iterations,
                "composition_mode": composition_mode,
                "tags": convert_and_respect_annotation_metadata(
                    object_=tags, annotation=AgentTagUpdateParams, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Agent,
                    parse_obj_as(
                        type_=Agent,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
