# 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.session import Session
from ..core.pydantic_utilities import parse_obj_as
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..core.jsonable_encoder import jsonable_encoder
from ..errors.not_found_error import NotFoundError
from ..types.consumption_offsets_update_params import ConsumptionOffsetsUpdateParams
from ..types.session_mode_dto import SessionModeDto
from ..core.serialization import convert_and_respect_annotation_metadata
from ..types.event_source_dto import EventSourceDto
from ..types.event import Event
from ..errors.gateway_timeout_error import GatewayTimeoutError
from ..types.event_kind_dto import EventKindDto
from ..types.moderation import Moderation
from ..types.agent_message_guideline import AgentMessageGuideline
from ..types.participant import Participant
from ..types.session_status_dto import SessionStatusDto
from ..core.client_wrapper import AsyncClientWrapper

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


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

    def list(
        self,
        *,
        agent_id: typing.Optional[str] = None,
        customer_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Session]:
        """
        Lists all sessions matching the specified filters.

        Can filter by agent_id and/or customer_id. Returns all sessions if no
        filters are provided.

        Parameters
        ----------
        agent_id : typing.Optional[str]

        customer_id : typing.Optional[str]

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

        Returns
        -------
        typing.List[Session]
            List of all matching sessions

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

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.sessions.list(
            agent_id="ag_123xyz",
            customer_id="cust_123xy",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "sessions",
            method="GET",
            params={
                "agent_id": agent_id,
                "customer_id": customer_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Session],
                    parse_obj_as(
                        type_=typing.List[Session],  # 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 create(
        self,
        *,
        agent_id: str,
        allow_greeting: typing.Optional[bool] = None,
        customer_id: typing.Optional[str] = OMIT,
        title: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Session:
        """
        Creates a new session between an agent and customer.

        The session will be initialized with the specified agent and optional customer.
        If no customer_id is provided, a guest customer will be created.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent associated with the session.

        allow_greeting : typing.Optional[bool]
            Whether to allow the agent to send an initial greeting

        customer_id : typing.Optional[str]
             ID of the customer this session belongs to. If not provided, a guest customer will be created.

        title : typing.Optional[str]
            Descriptive title for the session

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

        Returns
        -------
        Session
            Session successfully created. Returns the complete session object.

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

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.sessions.create(
            agent_id="ag_123xyz",
            customer_id="cust_123xy",
            title="Product inquiry session",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "sessions",
            method="POST",
            params={
                "allow_greeting": allow_greeting,
            },
            json={
                "agent_id": agent_id,
                "customer_id": customer_id,
                "title": title,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Session,
                    parse_obj_as(
                        type_=Session,  # 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_many(
        self,
        *,
        agent_id: typing.Optional[str] = None,
        customer_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes all sessions matching the specified filters.

        Can filter by agent_id and/or customer_id. Will delete all sessions if no
        filters are provided.

        Parameters
        ----------
        agent_id : typing.Optional[str]

        customer_id : typing.Optional[str]

        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.sessions.delete_many(
            agent_id="ag_123xyz",
            customer_id="cust_123xy",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "sessions",
            method="DELETE",
            params={
                "agent_id": agent_id,
                "customer_id": customer_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            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,
        session_id: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Session:
        """
        Retrieves details of a specific session by ID.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

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

        Returns
        -------
        Session
            Session details successfully retrieved

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

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.sessions.retrieve(
            session_id="sess_123yz",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Session,
                    parse_obj_as(
                        type_=Session,  # 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,
        session_id: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes a session and all its associated events.

        The operation is idempotent - deleting a non-existent session will return 404.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        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.sessions.delete(
            session_id="sess_123yz",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_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,
        session_id: str,
        *,
        consumption_offsets: typing.Optional[ConsumptionOffsetsUpdateParams] = OMIT,
        title: typing.Optional[str] = OMIT,
        mode: typing.Optional[SessionModeDto] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Session:
        """
        Updates an existing session's attributes.

        Only provided attributes will be updated; others remain unchanged.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        consumption_offsets : typing.Optional[ConsumptionOffsetsUpdateParams]

        title : typing.Optional[str]
            Descriptive title for the session

        mode : typing.Optional[SessionModeDto]
            The mode of the session, either 'auto' or 'manual'. In manual mode, events added to a session will not be responded to automatically by the agent.

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

        Returns
        -------
        Session
            Session successfully updated

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

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.sessions.update(
            session_id="sess_123yz",
            consumption_offsets=ConsumptionOffsetsUpdateParams(
                client=42,
            ),
            title="Updated session title",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}",
            method="PATCH",
            json={
                "consumption_offsets": convert_and_respect_annotation_metadata(
                    object_=consumption_offsets,
                    annotation=ConsumptionOffsetsUpdateParams,
                    direction="write",
                ),
                "title": title,
                "mode": mode,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Session,
                    parse_obj_as(
                        type_=Session,  # 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 list_events(
        self,
        session_id: str,
        *,
        min_offset: typing.Optional[int] = None,
        source: typing.Optional[EventSourceDto] = None,
        correlation_id: typing.Optional[str] = None,
        kinds: typing.Optional[str] = None,
        wait_for_data: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Event]:
        """
        Lists events from a session with optional filtering and waiting capabilities.

        This endpoint retrieves events from a specified session and can:
        1. Filter events by their offset, source, type, and correlation ID
        2. Wait for new events to arrive if requested
        3. Return events in chronological order based on their offset

        Notes:
            Long Polling Behavior:
            - When wait_for_data = 0:
                Returns immediately with any existing events that match the criteria
            - When wait_for_data > 0:
                - If new matching events arrive within the timeout period, returns with those events
                - If no new events arrive before timeout, raises 504 Gateway Timeout
                - If matching events already exist, returns immediately with those events

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        min_offset : typing.Optional[int]

        source : typing.Optional[EventSourceDto]

        correlation_id : typing.Optional[str]

        kinds : typing.Optional[str]

        wait_for_data : typing.Optional[int]

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

        Returns
        -------
        typing.List[Event]
            List of events matching the specified criteria

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

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.sessions.list_events(
            session_id="sess_123yz",
            min_offset=0,
            correlation_id="corr_13xyz",
            kinds="message,tool",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}/events",
            method="GET",
            params={
                "min_offset": min_offset,
                "source": source,
                "correlation_id": correlation_id,
                "kinds": kinds,
                "wait_for_data": wait_for_data,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Event],
                    parse_obj_as(
                        type_=typing.List[Event],  # 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(),
                        ),
                    )
                )
            if _response.status_code == 504:
                raise GatewayTimeoutError(
                    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 create_event(
        self,
        session_id: str,
        *,
        kind: EventKindDto,
        source: EventSourceDto,
        moderation: typing.Optional[Moderation] = None,
        message: typing.Optional[str] = OMIT,
        data: typing.Optional[typing.Optional[typing.Any]] = OMIT,
        guidelines: typing.Optional[typing.Sequence[AgentMessageGuideline]] = OMIT,
        participant: typing.Optional[Participant] = OMIT,
        status: typing.Optional[SessionStatusDto] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Event:
        """
        Creates a new event in the specified session.

        Currently supports creating message events from customer and human agent sources.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        kind : EventKindDto

        source : EventSourceDto

        moderation : typing.Optional[Moderation]
            Content moderation level for the event

        message : typing.Optional[str]
            Event payload data, format depends on kind

        data : typing.Optional[typing.Optional[typing.Any]]

        guidelines : typing.Optional[typing.Sequence[AgentMessageGuideline]]

        participant : typing.Optional[Participant]

        status : typing.Optional[SessionStatusDto]

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

        Returns
        -------
        Event
            Event successfully created

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

        client = ParlantClient(
            base_url="https://yourhost.com/path/to/api",
        )
        client.sessions.create_event(
            session_id="sess_123yz",
            kind="message",
            source="customer",
            message="Hello, I need help with my order",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}/events",
            method="POST",
            params={
                "moderation": moderation,
            },
            json={
                "kind": kind,
                "source": source,
                "message": message,
                "data": data,
                "guidelines": convert_and_respect_annotation_metadata(
                    object_=guidelines,
                    annotation=typing.Sequence[AgentMessageGuideline],
                    direction="write",
                ),
                "participant": convert_and_respect_annotation_metadata(
                    object_=participant, annotation=Participant, direction="write"
                ),
                "status": status,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Event,
                    parse_obj_as(
                        type_=Event,  # 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_events(
        self,
        session_id: str,
        *,
        min_offset: int,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes events from a session with offset >= the specified value.

        This operation is permanent and cannot be undone.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        min_offset : int
            Only return events with offset >= this value

        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.sessions.delete_events(
            session_id="sess_123yz",
            min_offset=0,
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}/events",
            method="DELETE",
            params={
                "min_offset": min_offset,
            },
            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)


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

    async def list(
        self,
        *,
        agent_id: typing.Optional[str] = None,
        customer_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Session]:
        """
        Lists all sessions matching the specified filters.

        Can filter by agent_id and/or customer_id. Returns all sessions if no
        filters are provided.

        Parameters
        ----------
        agent_id : typing.Optional[str]

        customer_id : typing.Optional[str]

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

        Returns
        -------
        typing.List[Session]
            List of all matching sessions

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

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


        async def main() -> None:
            await client.sessions.list(
                agent_id="ag_123xyz",
                customer_id="cust_123xy",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "sessions",
            method="GET",
            params={
                "agent_id": agent_id,
                "customer_id": customer_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Session],
                    parse_obj_as(
                        type_=typing.List[Session],  # 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 create(
        self,
        *,
        agent_id: str,
        allow_greeting: typing.Optional[bool] = None,
        customer_id: typing.Optional[str] = OMIT,
        title: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Session:
        """
        Creates a new session between an agent and customer.

        The session will be initialized with the specified agent and optional customer.
        If no customer_id is provided, a guest customer will be created.

        Parameters
        ----------
        agent_id : str
            Unique identifier for the agent associated with the session.

        allow_greeting : typing.Optional[bool]
            Whether to allow the agent to send an initial greeting

        customer_id : typing.Optional[str]
             ID of the customer this session belongs to. If not provided, a guest customer will be created.

        title : typing.Optional[str]
            Descriptive title for the session

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

        Returns
        -------
        Session
            Session successfully created. Returns the complete session 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.sessions.create(
                agent_id="ag_123xyz",
                customer_id="cust_123xy",
                title="Product inquiry session",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "sessions",
            method="POST",
            params={
                "allow_greeting": allow_greeting,
            },
            json={
                "agent_id": agent_id,
                "customer_id": customer_id,
                "title": title,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Session,
                    parse_obj_as(
                        type_=Session,  # 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_many(
        self,
        *,
        agent_id: typing.Optional[str] = None,
        customer_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes all sessions matching the specified filters.

        Can filter by agent_id and/or customer_id. Will delete all sessions if no
        filters are provided.

        Parameters
        ----------
        agent_id : typing.Optional[str]

        customer_id : typing.Optional[str]

        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.sessions.delete_many(
                agent_id="ag_123xyz",
                customer_id="cust_123xy",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "sessions",
            method="DELETE",
            params={
                "agent_id": agent_id,
                "customer_id": customer_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            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,
        session_id: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Session:
        """
        Retrieves details of a specific session by ID.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

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

        Returns
        -------
        Session
            Session details successfully retrieved

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

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


        async def main() -> None:
            await client.sessions.retrieve(
                session_id="sess_123yz",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Session,
                    parse_obj_as(
                        type_=Session,  # 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,
        session_id: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes a session and all its associated events.

        The operation is idempotent - deleting a non-existent session will return 404.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        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.sessions.delete(
                session_id="sess_123yz",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_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,
        session_id: str,
        *,
        consumption_offsets: typing.Optional[ConsumptionOffsetsUpdateParams] = OMIT,
        title: typing.Optional[str] = OMIT,
        mode: typing.Optional[SessionModeDto] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Session:
        """
        Updates an existing session's attributes.

        Only provided attributes will be updated; others remain unchanged.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        consumption_offsets : typing.Optional[ConsumptionOffsetsUpdateParams]

        title : typing.Optional[str]
            Descriptive title for the session

        mode : typing.Optional[SessionModeDto]
            The mode of the session, either 'auto' or 'manual'. In manual mode, events added to a session will not be responded to automatically by the agent.

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

        Returns
        -------
        Session
            Session successfully updated

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient, ConsumptionOffsetsUpdateParams

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


        async def main() -> None:
            await client.sessions.update(
                session_id="sess_123yz",
                consumption_offsets=ConsumptionOffsetsUpdateParams(
                    client=42,
                ),
                title="Updated session title",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}",
            method="PATCH",
            json={
                "consumption_offsets": convert_and_respect_annotation_metadata(
                    object_=consumption_offsets,
                    annotation=ConsumptionOffsetsUpdateParams,
                    direction="write",
                ),
                "title": title,
                "mode": mode,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Session,
                    parse_obj_as(
                        type_=Session,  # 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 list_events(
        self,
        session_id: str,
        *,
        min_offset: typing.Optional[int] = None,
        source: typing.Optional[EventSourceDto] = None,
        correlation_id: typing.Optional[str] = None,
        kinds: typing.Optional[str] = None,
        wait_for_data: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[Event]:
        """
        Lists events from a session with optional filtering and waiting capabilities.

        This endpoint retrieves events from a specified session and can:
        1. Filter events by their offset, source, type, and correlation ID
        2. Wait for new events to arrive if requested
        3. Return events in chronological order based on their offset

        Notes:
            Long Polling Behavior:
            - When wait_for_data = 0:
                Returns immediately with any existing events that match the criteria
            - When wait_for_data > 0:
                - If new matching events arrive within the timeout period, returns with those events
                - If no new events arrive before timeout, raises 504 Gateway Timeout
                - If matching events already exist, returns immediately with those events

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        min_offset : typing.Optional[int]

        source : typing.Optional[EventSourceDto]

        correlation_id : typing.Optional[str]

        kinds : typing.Optional[str]

        wait_for_data : typing.Optional[int]

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

        Returns
        -------
        typing.List[Event]
            List of events matching the specified criteria

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

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


        async def main() -> None:
            await client.sessions.list_events(
                session_id="sess_123yz",
                min_offset=0,
                correlation_id="corr_13xyz",
                kinds="message,tool",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}/events",
            method="GET",
            params={
                "min_offset": min_offset,
                "source": source,
                "correlation_id": correlation_id,
                "kinds": kinds,
                "wait_for_data": wait_for_data,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Event],
                    parse_obj_as(
                        type_=typing.List[Event],  # 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(),
                        ),
                    )
                )
            if _response.status_code == 504:
                raise GatewayTimeoutError(
                    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 create_event(
        self,
        session_id: str,
        *,
        kind: EventKindDto,
        source: EventSourceDto,
        moderation: typing.Optional[Moderation] = None,
        message: typing.Optional[str] = OMIT,
        data: typing.Optional[typing.Optional[typing.Any]] = OMIT,
        guidelines: typing.Optional[typing.Sequence[AgentMessageGuideline]] = OMIT,
        participant: typing.Optional[Participant] = OMIT,
        status: typing.Optional[SessionStatusDto] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> Event:
        """
        Creates a new event in the specified session.

        Currently supports creating message events from customer and human agent sources.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        kind : EventKindDto

        source : EventSourceDto

        moderation : typing.Optional[Moderation]
            Content moderation level for the event

        message : typing.Optional[str]
            Event payload data, format depends on kind

        data : typing.Optional[typing.Optional[typing.Any]]

        guidelines : typing.Optional[typing.Sequence[AgentMessageGuideline]]

        participant : typing.Optional[Participant]

        status : typing.Optional[SessionStatusDto]

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

        Returns
        -------
        Event
            Event successfully created

        Examples
        --------
        import asyncio

        from parlant.client import AsyncParlantClient

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


        async def main() -> None:
            await client.sessions.create_event(
                session_id="sess_123yz",
                kind="message",
                source="customer",
                message="Hello, I need help with my order",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}/events",
            method="POST",
            params={
                "moderation": moderation,
            },
            json={
                "kind": kind,
                "source": source,
                "message": message,
                "data": data,
                "guidelines": convert_and_respect_annotation_metadata(
                    object_=guidelines,
                    annotation=typing.Sequence[AgentMessageGuideline],
                    direction="write",
                ),
                "participant": convert_and_respect_annotation_metadata(
                    object_=participant, annotation=Participant, direction="write"
                ),
                "status": status,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Event,
                    parse_obj_as(
                        type_=Event,  # 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_events(
        self,
        session_id: str,
        *,
        min_offset: int,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> None:
        """
        Deletes events from a session with offset >= the specified value.

        This operation is permanent and cannot be undone.

        Parameters
        ----------
        session_id : str
            Unique identifier for the session

        min_offset : int
            Only return events with offset >= this value

        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.sessions.delete_events(
                session_id="sess_123yz",
                min_offset=0,
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"sessions/{jsonable_encoder(session_id)}/events",
            method="DELETE",
            params={
                "min_offset": min_offset,
            },
            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)
