r"""
    This code was generated by
   ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
    |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
    |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \

    Twilio - Assistants
    This is the public Twilio REST API.

    NOTE: This class is auto generated by OpenAPI Generator.
    https://openapi-generator.tech
    Do not edit the class manually.
"""

from datetime import datetime
from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator
from twilio.base import deserialize, values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.version import Version
from twilio.base.page import Page
from twilio.rest.assistants.v1.assistant.assistants_knowledge import (
    AssistantsKnowledgeList,
)
from twilio.rest.assistants.v1.assistant.assistants_tool import AssistantsToolList
from twilio.rest.assistants.v1.assistant.feedback import FeedbackList
from twilio.rest.assistants.v1.assistant.message import MessageList


class AssistantInstance(InstanceResource):
    """
    :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Assistant resource.
    :ivar customer_ai: The Personalization and Perception Engine settings.
    :ivar id: The Assistant ID.
    :ivar model: The default model used by the assistant.
    :ivar name: The name of the assistant.
    :ivar owner: The owner/company of the assistant.
    :ivar url: The url of the assistant resource.
    :ivar personality_prompt: The personality prompt to be used for assistant.
    :ivar date_created: The date and time in GMT when the Assistant was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format.
    :ivar date_updated: The date and time in GMT when the Assistant was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format.
    :ivar knowledge: The list of knowledge sources associated with the assistant.
    :ivar tools: The list of tools associated with the assistant.
    """

    def __init__(
        self, version: Version, payload: Dict[str, Any], id: Optional[str] = None
    ):
        super().__init__(version)

        self.account_sid: Optional[str] = payload.get("account_sid")
        self.customer_ai: Optional[Dict[str, object]] = payload.get("customer_ai")
        self.id: Optional[str] = payload.get("id")
        self.model: Optional[str] = payload.get("model")
        self.name: Optional[str] = payload.get("name")
        self.owner: Optional[str] = payload.get("owner")
        self.url: Optional[str] = payload.get("url")
        self.personality_prompt: Optional[str] = payload.get("personality_prompt")
        self.date_created: Optional[datetime] = deserialize.iso8601_datetime(
            payload.get("date_created")
        )
        self.date_updated: Optional[datetime] = deserialize.iso8601_datetime(
            payload.get("date_updated")
        )
        self.knowledge: Optional[List[str]] = payload.get("knowledge")
        self.tools: Optional[List[str]] = payload.get("tools")

        self._solution = {
            "id": id or self.id,
        }
        self._context: Optional[AssistantContext] = None

    @property
    def _proxy(self) -> "AssistantContext":
        """
        Generate an instance context for the instance, the context is capable of
        performing various actions. All instance actions are proxied to the context

        :returns: AssistantContext for this AssistantInstance
        """
        if self._context is None:
            self._context = AssistantContext(
                self._version,
                id=self._solution["id"],
            )
        return self._context

    def delete(self) -> bool:
        """
        Deletes the AssistantInstance


        :returns: True if delete succeeds, False otherwise
        """
        return self._proxy.delete()

    async def delete_async(self) -> bool:
        """
        Asynchronous coroutine that deletes the AssistantInstance


        :returns: True if delete succeeds, False otherwise
        """
        return await self._proxy.delete_async()

    def fetch(self) -> "AssistantInstance":
        """
        Fetch the AssistantInstance


        :returns: The fetched AssistantInstance
        """
        return self._proxy.fetch()

    async def fetch_async(self) -> "AssistantInstance":
        """
        Asynchronous coroutine to fetch the AssistantInstance


        :returns: The fetched AssistantInstance
        """
        return await self._proxy.fetch_async()

    def update(
        self,
        assistants_v1_service_update_assistant_request: Union[
            AssistantsV1ServiceUpdateAssistantRequest, object
        ] = values.unset,
    ) -> "AssistantInstance":
        """
        Update the AssistantInstance

        :param assistants_v1_service_update_assistant_request:

        :returns: The updated AssistantInstance
        """
        return self._proxy.update(
            assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request,
        )

    async def update_async(
        self,
        assistants_v1_service_update_assistant_request: Union[
            AssistantsV1ServiceUpdateAssistantRequest, object
        ] = values.unset,
    ) -> "AssistantInstance":
        """
        Asynchronous coroutine to update the AssistantInstance

        :param assistants_v1_service_update_assistant_request:

        :returns: The updated AssistantInstance
        """
        return await self._proxy.update_async(
            assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request,
        )

    @property
    def assistants_knowledge(self) -> AssistantsKnowledgeList:
        """
        Access the assistants_knowledge
        """
        return self._proxy.assistants_knowledge

    @property
    def assistants_tools(self) -> AssistantsToolList:
        """
        Access the assistants_tools
        """
        return self._proxy.assistants_tools

    @property
    def feedbacks(self) -> FeedbackList:
        """
        Access the feedbacks
        """
        return self._proxy.feedbacks

    @property
    def messages(self) -> MessageList:
        """
        Access the messages
        """
        return self._proxy.messages

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        context = " ".join("{}={}".format(k, v) for k, v in self._solution.items())
        return "<Twilio.Assistants.V1.AssistantInstance {}>".format(context)


class AssistantContext(InstanceContext):

    def __init__(self, version: Version, id: str):
        """
        Initialize the AssistantContext

        :param version: Version that contains the resource
        :param id:
        """
        super().__init__(version)

        # Path Solution
        self._solution = {
            "id": id,
        }
        self._uri = "/Assistants/{id}".format(**self._solution)

        self._assistants_knowledge: Optional[AssistantsKnowledgeList] = None
        self._assistants_tools: Optional[AssistantsToolList] = None
        self._feedbacks: Optional[FeedbackList] = None
        self._messages: Optional[MessageList] = None

    def delete(self) -> bool:
        """
        Deletes the AssistantInstance


        :returns: True if delete succeeds, False otherwise
        """
        return self._version.delete(
            method="DELETE",
            uri=self._uri,
        )

    async def delete_async(self) -> bool:
        """
        Asynchronous coroutine that deletes the AssistantInstance


        :returns: True if delete succeeds, False otherwise
        """
        return await self._version.delete_async(
            method="DELETE",
            uri=self._uri,
        )

    def fetch(self) -> AssistantInstance:
        """
        Fetch the AssistantInstance


        :returns: The fetched AssistantInstance
        """

        payload = self._version.fetch(
            method="GET",
            uri=self._uri,
        )

        return AssistantInstance(
            self._version,
            payload,
            id=self._solution["id"],
        )

    async def fetch_async(self) -> AssistantInstance:
        """
        Asynchronous coroutine to fetch the AssistantInstance


        :returns: The fetched AssistantInstance
        """

        payload = await self._version.fetch_async(
            method="GET",
            uri=self._uri,
        )

        return AssistantInstance(
            self._version,
            payload,
            id=self._solution["id"],
        )

    def update(
        self,
        assistants_v1_service_update_assistant_request: Union[
            AssistantsV1ServiceUpdateAssistantRequest, object
        ] = values.unset,
    ) -> AssistantInstance:
        """
        Update the AssistantInstance

        :param assistants_v1_service_update_assistant_request:

        :returns: The updated AssistantInstance
        """
        data = values.of({})
        headers = values.of(
            {
                "AssistantsV1ServiceUpdateAssistantRequest": assistants_v1_service_update_assistant_request,
            }
        )

        payload = self._version.update(
            method="PUT", uri=self._uri, data=data, headers=headers
        )

        return AssistantInstance(self._version, payload, id=self._solution["id"])

    async def update_async(
        self,
        assistants_v1_service_update_assistant_request: Union[
            AssistantsV1ServiceUpdateAssistantRequest, object
        ] = values.unset,
    ) -> AssistantInstance:
        """
        Asynchronous coroutine to update the AssistantInstance

        :param assistants_v1_service_update_assistant_request:

        :returns: The updated AssistantInstance
        """
        data = values.of({})
        headers = values.of(
            {
                "AssistantsV1ServiceUpdateAssistantRequest": assistants_v1_service_update_assistant_request,
            }
        )

        payload = await self._version.update_async(
            method="PUT", uri=self._uri, data=data, headers=headers
        )

        return AssistantInstance(self._version, payload, id=self._solution["id"])

    @property
    def assistants_knowledge(self) -> AssistantsKnowledgeList:
        """
        Access the assistants_knowledge
        """
        if self._assistants_knowledge is None:
            self._assistants_knowledge = AssistantsKnowledgeList(
                self._version,
                self._solution["id"],
            )
        return self._assistants_knowledge

    @property
    def assistants_tools(self) -> AssistantsToolList:
        """
        Access the assistants_tools
        """
        if self._assistants_tools is None:
            self._assistants_tools = AssistantsToolList(
                self._version,
                self._solution["id"],
            )
        return self._assistants_tools

    @property
    def feedbacks(self) -> FeedbackList:
        """
        Access the feedbacks
        """
        if self._feedbacks is None:
            self._feedbacks = FeedbackList(
                self._version,
                self._solution["id"],
            )
        return self._feedbacks

    @property
    def messages(self) -> MessageList:
        """
        Access the messages
        """
        if self._messages is None:
            self._messages = MessageList(
                self._version,
                self._solution["id"],
            )
        return self._messages

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        context = " ".join("{}={}".format(k, v) for k, v in self._solution.items())
        return "<Twilio.Assistants.V1.AssistantContext {}>".format(context)


class AssistantPage(Page):

    def get_instance(self, payload: Dict[str, Any]) -> AssistantInstance:
        """
        Build an instance of AssistantInstance

        :param payload: Payload response from the API
        """
        return AssistantInstance(self._version, payload)

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.Assistants.V1.AssistantPage>"


class AssistantList(ListResource):

    class AssistantsV1ServiceCreateAssistantRequest(object):
        """
        :ivar customer_ai:
        :ivar name: The name of the assistant.
        :ivar owner: The owner/company of the assistant.
        :ivar personality_prompt: The personality prompt to be used for assistant.
        :ivar segment_credential:
        """

        def __init__(self, payload: Dict[str, Any]):

            self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = (
                payload.get("customer_ai")
            )
            self.name: Optional[str] = payload.get("name")
            self.owner: Optional[str] = payload.get("owner")
            self.personality_prompt: Optional[str] = payload.get("personality_prompt")
            self.segment_credential: Optional[
                AssistantList.AssistantsV1ServiceSegmentCredential
            ] = payload.get("segment_credential")

        def to_dict(self):
            return {
                "customer_ai": self.customer_ai.to_dict(),
                "name": self.name,
                "owner": self.owner,
                "personality_prompt": self.personality_prompt,
                "segment_credential": self.segment_credential.to_dict(),
            }

    class AssistantsV1ServiceCustomerAi(object):
        """
        :ivar perception_engine_enabled: True if the perception engine is enabled.
        :ivar personalization_engine_enabled: True if the personalization engine is enabled.
        """

        def __init__(self, payload: Dict[str, Any]):

            self.perception_engine_enabled: Optional[bool] = payload.get(
                "perception_engine_enabled"
            )
            self.personalization_engine_enabled: Optional[bool] = payload.get(
                "personalization_engine_enabled"
            )

        def to_dict(self):
            return {
                "perception_engine_enabled": self.perception_engine_enabled,
                "personalization_engine_enabled": self.personalization_engine_enabled,
            }

    class AssistantsV1ServiceSegmentCredential(object):
        """
        :ivar profile_api_key: The profile API key.
        :ivar space_id: The space ID.
        :ivar write_key: The write key.
        """

        def __init__(self, payload: Dict[str, Any]):

            self.profile_api_key: Optional[str] = payload.get("profile_api_key")
            self.space_id: Optional[str] = payload.get("space_id")
            self.write_key: Optional[str] = payload.get("write_key")

        def to_dict(self):
            return {
                "profile_api_key": self.profile_api_key,
                "space_id": self.space_id,
                "write_key": self.write_key,
            }

    class AssistantsV1ServiceUpdateAssistantRequest(object):
        """
        :ivar customer_ai:
        :ivar name: The name of the assistant.
        :ivar owner: The owner/company of the assistant.
        :ivar personality_prompt: The personality prompt to be used for assistant.
        :ivar segment_credential:
        """

        def __init__(self, payload: Dict[str, Any]):

            self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = (
                payload.get("customer_ai")
            )
            self.name: Optional[str] = payload.get("name")
            self.owner: Optional[str] = payload.get("owner")
            self.personality_prompt: Optional[str] = payload.get("personality_prompt")
            self.segment_credential: Optional[
                AssistantList.AssistantsV1ServiceSegmentCredential
            ] = payload.get("segment_credential")

        def to_dict(self):
            return {
                "customer_ai": self.customer_ai.to_dict(),
                "name": self.name,
                "owner": self.owner,
                "personality_prompt": self.personality_prompt,
                "segment_credential": self.segment_credential.to_dict(),
            }

    def __init__(self, version: Version):
        """
        Initialize the AssistantList

        :param version: Version that contains the resource

        """
        super().__init__(version)

        self._uri = "/Assistants"

    def create(
        self,
        assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest,
    ) -> AssistantInstance:
        """
        Create the AssistantInstance

        :param assistants_v1_service_create_assistant_request:

        :returns: The created AssistantInstance
        """
        data = assistants_v1_service_create_assistant_request.to_dict()

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})
        headers["Content-Type"] = "application/json"

        payload = self._version.create(
            method="POST", uri=self._uri, data=data, headers=headers
        )

        return AssistantInstance(self._version, payload)

    async def create_async(
        self,
        assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest,
    ) -> AssistantInstance:
        """
        Asynchronously create the AssistantInstance

        :param assistants_v1_service_create_assistant_request:

        :returns: The created AssistantInstance
        """
        data = assistants_v1_service_create_assistant_request.to_dict()

        headers = values.of({"Content-Type": "application/x-www-form-urlencoded"})
        headers["Content-Type"] = "application/json"

        payload = await self._version.create_async(
            method="POST", uri=self._uri, data=data, headers=headers
        )

        return AssistantInstance(self._version, payload)

    def stream(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> Iterator[AssistantInstance]:
        """
        Streams AssistantInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = self.page(page_size=limits["page_size"])

        return self._version.stream(page, limits["limit"])

    async def stream_async(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> AsyncIterator[AssistantInstance]:
        """
        Asynchronously streams AssistantInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = await self.page_async(page_size=limits["page_size"])

        return self._version.stream_async(page, limits["limit"])

    def list(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[AssistantInstance]:
        """
        Lists AssistantInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return list(
            self.stream(
                limit=limit,
                page_size=page_size,
            )
        )

    async def list_async(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[AssistantInstance]:
        """
        Asynchronously lists AssistantInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return [
            record
            async for record in await self.stream_async(
                limit=limit,
                page_size=page_size,
            )
        ]

    def page(
        self,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> AssistantPage:
        """
        Retrieve a single page of AssistantInstance records from the API.
        Request is executed immediately

        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of AssistantInstance
        """
        data = values.of(
            {
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        response = self._version.page(method="GET", uri=self._uri, params=data)
        return AssistantPage(self._version, response)

    async def page_async(
        self,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> AssistantPage:
        """
        Asynchronously retrieve a single page of AssistantInstance records from the API.
        Request is executed immediately

        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of AssistantInstance
        """
        data = values.of(
            {
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        response = await self._version.page_async(
            method="GET", uri=self._uri, params=data
        )
        return AssistantPage(self._version, response)

    def get_page(self, target_url: str) -> AssistantPage:
        """
        Retrieve a specific page of AssistantInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of AssistantInstance
        """
        response = self._version.domain.twilio.request("GET", target_url)
        return AssistantPage(self._version, response)

    async def get_page_async(self, target_url: str) -> AssistantPage:
        """
        Asynchronously retrieve a specific page of AssistantInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of AssistantInstance
        """
        response = await self._version.domain.twilio.request_async("GET", target_url)
        return AssistantPage(self._version, response)

    def get(self, id: str) -> AssistantContext:
        """
        Constructs a AssistantContext

        :param id:
        """
        return AssistantContext(self._version, id=id)

    def __call__(self, id: str) -> AssistantContext:
        """
        Constructs a AssistantContext

        :param id:
        """
        return AssistantContext(self._version, id=id)

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.Assistants.V1.AssistantList>"
