# 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.payment_required_error import PaymentRequiredError
from ...types.payment_required_error_body import PaymentRequiredErrorBody
from .types.agents_create_request_initial_message_sequence_item import AgentsCreateRequestInitialMessageSequenceItem
from .types.agents_create_response import AgentsCreateResponse

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


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

    def create(
        self,
        project: str,
        template_version: str,
        *,
        tags: typing.Optional[typing.Sequence[str]] = OMIT,
        agent_name: typing.Optional[str] = OMIT,
        initial_message_sequence: typing.Optional[
            typing.Sequence[AgentsCreateRequestInitialMessageSequenceItem]
        ] = OMIT,
        memory_variables: typing.Optional[typing.Dict[str, str]] = OMIT,
        tool_variables: typing.Optional[typing.Dict[str, str]] = OMIT,
        identity_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[AgentsCreateResponse]:
        """
        Creates an Agent or multiple Agents from a template

        Parameters
        ----------
        project : str
            The project slug

        template_version : str
            The template version, formatted as {template-name}:{version-number} or {template-name}:latest

        tags : typing.Optional[typing.Sequence[str]]
            The tags to assign to the agent

        agent_name : typing.Optional[str]
            The name of the agent, optional otherwise a random one will be assigned

        initial_message_sequence : typing.Optional[typing.Sequence[AgentsCreateRequestInitialMessageSequenceItem]]
            Set an initial sequence of messages, if not provided, the agent will start with the default message sequence, if an empty array is provided, the agent will start with no messages

        memory_variables : typing.Optional[typing.Dict[str, str]]
            The memory variables to assign to the agent

        tool_variables : typing.Optional[typing.Dict[str, str]]
            The tool variables to assign to the agent

        identity_ids : typing.Optional[typing.Sequence[str]]
            The identity ids to assign to the agent

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

        Returns
        -------
        HttpResponse[AgentsCreateResponse]
            201
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/templates/{jsonable_encoder(project)}/{jsonable_encoder(template_version)}/agents",
            method="POST",
            json={
                "tags": tags,
                "agent_name": agent_name,
                "initial_message_sequence": convert_and_respect_annotation_metadata(
                    object_=initial_message_sequence,
                    annotation=typing.Sequence[AgentsCreateRequestInitialMessageSequenceItem],
                    direction="write",
                ),
                "memory_variables": memory_variables,
                "tool_variables": tool_variables,
                "identity_ids": identity_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AgentsCreateResponse,
                    construct_type(
                        type_=AgentsCreateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 402:
                raise PaymentRequiredError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PaymentRequiredErrorBody,
                        construct_type(
                            type_=PaymentRequiredErrorBody,  # 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 AsyncRawAgentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def create(
        self,
        project: str,
        template_version: str,
        *,
        tags: typing.Optional[typing.Sequence[str]] = OMIT,
        agent_name: typing.Optional[str] = OMIT,
        initial_message_sequence: typing.Optional[
            typing.Sequence[AgentsCreateRequestInitialMessageSequenceItem]
        ] = OMIT,
        memory_variables: typing.Optional[typing.Dict[str, str]] = OMIT,
        tool_variables: typing.Optional[typing.Dict[str, str]] = OMIT,
        identity_ids: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AgentsCreateResponse]:
        """
        Creates an Agent or multiple Agents from a template

        Parameters
        ----------
        project : str
            The project slug

        template_version : str
            The template version, formatted as {template-name}:{version-number} or {template-name}:latest

        tags : typing.Optional[typing.Sequence[str]]
            The tags to assign to the agent

        agent_name : typing.Optional[str]
            The name of the agent, optional otherwise a random one will be assigned

        initial_message_sequence : typing.Optional[typing.Sequence[AgentsCreateRequestInitialMessageSequenceItem]]
            Set an initial sequence of messages, if not provided, the agent will start with the default message sequence, if an empty array is provided, the agent will start with no messages

        memory_variables : typing.Optional[typing.Dict[str, str]]
            The memory variables to assign to the agent

        tool_variables : typing.Optional[typing.Dict[str, str]]
            The tool variables to assign to the agent

        identity_ids : typing.Optional[typing.Sequence[str]]
            The identity ids to assign to the agent

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

        Returns
        -------
        AsyncHttpResponse[AgentsCreateResponse]
            201
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/templates/{jsonable_encoder(project)}/{jsonable_encoder(template_version)}/agents",
            method="POST",
            json={
                "tags": tags,
                "agent_name": agent_name,
                "initial_message_sequence": convert_and_respect_annotation_metadata(
                    object_=initial_message_sequence,
                    annotation=typing.Sequence[AgentsCreateRequestInitialMessageSequenceItem],
                    direction="write",
                ),
                "memory_variables": memory_variables,
                "tool_variables": tool_variables,
                "identity_ids": identity_ids,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AgentsCreateResponse,
                    construct_type(
                        type_=AgentsCreateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 402:
                raise PaymentRequiredError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        PaymentRequiredErrorBody,
                        construct_type(
                            type_=PaymentRequiredErrorBody,  # 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)
