# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

from __future__ import annotations

from typing import Dict, List, Union
from datetime import datetime
from typing_extensions import Literal

import httpx

from ..types import call_list_params, call_create_params
from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
from .._utils import maybe_transform, async_maybe_transform
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
    to_raw_response_wrapper,
    to_streamed_response_wrapper,
    async_to_raw_response_wrapper,
    async_to_streamed_response_wrapper,
)
from .._base_client import make_request_options
from ..types.call_list_response import CallListResponse
from ..types.call_create_response import CallCreateResponse
from ..types.call_retrieve_response import CallRetrieveResponse

__all__ = ["CallResource", "AsyncCallResource"]


class CallResource(SyncAPIResource):
    @cached_property
    def with_raw_response(self) -> CallResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/revoxai/revox-python#accessing-raw-response-data-eg-headers
        """
        return CallResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> CallResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/revoxai/revox-python#with_streaming_response
        """
        return CallResourceWithStreamingResponse(self)

    def create(
        self,
        *,
        phone_number: str,
        assistant: call_create_params.Assistant | Omit = omit,
        assistant_id: str | Omit = omit,
        concurrency: call_create_params.Concurrency | Omit = omit,
        force_now: bool | Omit = omit,
        from_phone_number: str | Omit = omit,
        metadata: Dict[str, str] | Omit = omit,
        prompt_variables: Dict[str, str] | Omit = omit,
        scheduled_at: Union[Union[str, datetime], object] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> CallCreateResponse:
        """Place a new outbound call order.

        Provide either an existing assistant ID or a
        custom assistant configuration. The call can be scheduled for a specific time or
        started immediately. A single call order may be resolved over multiple call
        attempts spanning up to a few days, with automatic retries when voicemail is
        detected. You can also set concurrency limits and pass prompt variables for
        dynamic personalization.

        Args:
          phone_number: The phone number to call in the E.164 format. Example: +1234567890

          assistant: You can provide a custom assistant configuration here. If you don't provide an
              assistant_id, this assistant object will be used for this call.

          assistant_id: The ID of the assistant to use for this call.

          concurrency: Limit the number of concurrent calls for a given concurrency key.

          force_now: The prompt to use for the call. This will be given to the LLM (gpt-4.1)

          from_phone_number: The phone number to use for making the call (e.g., +1234567890). If not
              provided, uses the default trunk.

          metadata: Metadata to store with the call.

          prompt_variables: Variables to interpolate into the prompt. Wether you use an assistant_id or an
              assistant object, this will be used to interpolate the variables into the
              prompt.

          scheduled_at: Schedule the call to start at a specific date and time (ISO 8601 format). If not
              provided, the call will start immediately.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._post(
            "/call",
            body=maybe_transform(
                {
                    "phone_number": phone_number,
                    "assistant": assistant,
                    "assistant_id": assistant_id,
                    "concurrency": concurrency,
                    "force_now": force_now,
                    "from_phone_number": from_phone_number,
                    "metadata": metadata,
                    "prompt_variables": prompt_variables,
                    "scheduled_at": scheduled_at,
                },
                call_create_params.CallCreateParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=CallCreateResponse,
        )

    def retrieve(
        self,
        id: str,
        *,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> CallRetrieveResponse:
        """Retrieve the full details of a call order by its unique ID.

        The response
        includes the call status, call attempts, transcript, recording URL, timestamps,
        and metadata. Use this endpoint to poll for call completion or inspect results
        after a call has finished.

        Args:
          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not id:
            raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
        return self._get(
            f"/call/{id}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=CallRetrieveResponse,
        )

    def list(
        self,
        *,
        page: int,
        page_size: int,
        statuses: List[
            Literal["initializing", "queued_for_calling", "calling", "scheduled", "completed", "cancelled", "errored"]
        ]
        | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> CallListResponse:
        """Retrieve a paginated list of call attempts.

        Each entry includes the call status,
        phone number, assistant used, transcript, and timestamps. Use the page and
        page_size query parameters to navigate through results.

        Args:
          page: The page number you want to get. Starting at 0.

          page_size: The number of calls to return per page.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return self._get(
            "/call",
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "page": page,
                        "page_size": page_size,
                        "statuses": statuses,
                    },
                    call_list_params.CallListParams,
                ),
            ),
            cast_to=CallListResponse,
        )


class AsyncCallResource(AsyncAPIResource):
    @cached_property
    def with_raw_response(self) -> AsyncCallResourceWithRawResponse:
        """
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/revoxai/revox-python#accessing-raw-response-data-eg-headers
        """
        return AsyncCallResourceWithRawResponse(self)

    @cached_property
    def with_streaming_response(self) -> AsyncCallResourceWithStreamingResponse:
        """
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/revoxai/revox-python#with_streaming_response
        """
        return AsyncCallResourceWithStreamingResponse(self)

    async def create(
        self,
        *,
        phone_number: str,
        assistant: call_create_params.Assistant | Omit = omit,
        assistant_id: str | Omit = omit,
        concurrency: call_create_params.Concurrency | Omit = omit,
        force_now: bool | Omit = omit,
        from_phone_number: str | Omit = omit,
        metadata: Dict[str, str] | Omit = omit,
        prompt_variables: Dict[str, str] | Omit = omit,
        scheduled_at: Union[Union[str, datetime], object] | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> CallCreateResponse:
        """Place a new outbound call order.

        Provide either an existing assistant ID or a
        custom assistant configuration. The call can be scheduled for a specific time or
        started immediately. A single call order may be resolved over multiple call
        attempts spanning up to a few days, with automatic retries when voicemail is
        detected. You can also set concurrency limits and pass prompt variables for
        dynamic personalization.

        Args:
          phone_number: The phone number to call in the E.164 format. Example: +1234567890

          assistant: You can provide a custom assistant configuration here. If you don't provide an
              assistant_id, this assistant object will be used for this call.

          assistant_id: The ID of the assistant to use for this call.

          concurrency: Limit the number of concurrent calls for a given concurrency key.

          force_now: The prompt to use for the call. This will be given to the LLM (gpt-4.1)

          from_phone_number: The phone number to use for making the call (e.g., +1234567890). If not
              provided, uses the default trunk.

          metadata: Metadata to store with the call.

          prompt_variables: Variables to interpolate into the prompt. Wether you use an assistant_id or an
              assistant object, this will be used to interpolate the variables into the
              prompt.

          scheduled_at: Schedule the call to start at a specific date and time (ISO 8601 format). If not
              provided, the call will start immediately.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._post(
            "/call",
            body=await async_maybe_transform(
                {
                    "phone_number": phone_number,
                    "assistant": assistant,
                    "assistant_id": assistant_id,
                    "concurrency": concurrency,
                    "force_now": force_now,
                    "from_phone_number": from_phone_number,
                    "metadata": metadata,
                    "prompt_variables": prompt_variables,
                    "scheduled_at": scheduled_at,
                },
                call_create_params.CallCreateParams,
            ),
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=CallCreateResponse,
        )

    async def retrieve(
        self,
        id: str,
        *,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> CallRetrieveResponse:
        """Retrieve the full details of a call order by its unique ID.

        The response
        includes the call status, call attempts, transcript, recording URL, timestamps,
        and metadata. Use this endpoint to poll for call completion or inspect results
        after a call has finished.

        Args:
          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        if not id:
            raise ValueError(f"Expected a non-empty value for `id` but received {id!r}")
        return await self._get(
            f"/call/{id}",
            options=make_request_options(
                extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
            ),
            cast_to=CallRetrieveResponse,
        )

    async def list(
        self,
        *,
        page: int,
        page_size: int,
        statuses: List[
            Literal["initializing", "queued_for_calling", "calling", "scheduled", "completed", "cancelled", "errored"]
        ]
        | Omit = omit,
        # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
        # The extra values given here take precedence over values defined on the client or passed to this method.
        extra_headers: Headers | None = None,
        extra_query: Query | None = None,
        extra_body: Body | None = None,
        timeout: float | httpx.Timeout | None | NotGiven = not_given,
    ) -> CallListResponse:
        """Retrieve a paginated list of call attempts.

        Each entry includes the call status,
        phone number, assistant used, transcript, and timestamps. Use the page and
        page_size query parameters to navigate through results.

        Args:
          page: The page number you want to get. Starting at 0.

          page_size: The number of calls to return per page.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        """
        return await self._get(
            "/call",
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=await async_maybe_transform(
                    {
                        "page": page,
                        "page_size": page_size,
                        "statuses": statuses,
                    },
                    call_list_params.CallListParams,
                ),
            ),
            cast_to=CallListResponse,
        )


class CallResourceWithRawResponse:
    def __init__(self, call: CallResource) -> None:
        self._call = call

        self.create = to_raw_response_wrapper(
            call.create,
        )
        self.retrieve = to_raw_response_wrapper(
            call.retrieve,
        )
        self.list = to_raw_response_wrapper(
            call.list,
        )


class AsyncCallResourceWithRawResponse:
    def __init__(self, call: AsyncCallResource) -> None:
        self._call = call

        self.create = async_to_raw_response_wrapper(
            call.create,
        )
        self.retrieve = async_to_raw_response_wrapper(
            call.retrieve,
        )
        self.list = async_to_raw_response_wrapper(
            call.list,
        )


class CallResourceWithStreamingResponse:
    def __init__(self, call: CallResource) -> None:
        self._call = call

        self.create = to_streamed_response_wrapper(
            call.create,
        )
        self.retrieve = to_streamed_response_wrapper(
            call.retrieve,
        )
        self.list = to_streamed_response_wrapper(
            call.list,
        )


class AsyncCallResourceWithStreamingResponse:
    def __init__(self, call: AsyncCallResource) -> None:
        self._call = call

        self.create = async_to_streamed_response_wrapper(
            call.create,
        )
        self.retrieve = async_to_streamed_response_wrapper(
            call.retrieve,
        )
        self.list = async_to_streamed_response_wrapper(
            call.list,
        )
