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

from __future__ import annotations

from typing import Dict, Type, cast
from typing_extensions import Literal

import httpx

from ...._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given
from ...._utils import path_template, 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 ...._wrappers import ResultWrapper
from ....pagination import SyncV4PagePaginationArray, AsyncV4PagePaginationArray
from ...._base_client import AsyncPaginator, make_request_options
from ....types.api_gateway.discovery import operation_list_params, operation_bulk_edit_params
from ....types.api_gateway.discovery_operation import DiscoveryOperation
from ....types.api_gateway.discovery.operation_bulk_edit_response import OperationBulkEditResponse

__all__ = ["OperationsResource", "AsyncOperationsResource"]


class OperationsResource(SyncAPIResource):
    @cached_property
    def with_raw_response(self) -> OperationsResourceWithRawResponse:
        """
        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/cloudflare/cloudflare-python#accessing-raw-response-data-eg-headers
        """
        return OperationsResourceWithRawResponse(self)

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

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

    def list(
        self,
        *,
        zone_id: str,
        diff: bool | Omit = omit,
        direction: Literal["asc", "desc"] | Omit = omit,
        endpoint: str | Omit = omit,
        host: SequenceNotStr[str] | Omit = omit,
        method: SequenceNotStr[str] | Omit = omit,
        order: Literal["host", "method", "endpoint", "traffic_stats.requests", "traffic_stats.last_updated"]
        | Omit = omit,
        origin: Literal["ML", "SessionIdentifier", "LabelDiscovery"] | Omit = omit,
        page: int | Omit = omit,
        per_page: int | Omit = omit,
        state: Literal["review", "saved", "ignored"] | 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,
    ) -> SyncV4PagePaginationArray[DiscoveryOperation]:
        """
        Retrieve the most up to date view of discovered operations

        Args:
          zone_id: Identifier.

          diff: When `true`, only return API Discovery results that are not saved into API
              Shield Endpoint Management

          direction: Direction to order results.

          endpoint: Filter results to only include endpoints containing this pattern.

          host: Filter results to only include the specified hosts.

          method: Filter results to only include the specified HTTP methods.

          order: Field to order by

          origin: Filter results to only include discovery results sourced from a particular
              discovery engine

              - `ML` - Discovered operations that were sourced using ML API Discovery
              - `SessionIdentifier` - Discovered operations that were sourced using Session
                Identifier API Discovery

          page: Page number of paginated results.

          per_page: Maximum number of results per page.

          state: Filter results to only include discovery results in a particular state. States
              are as follows

              - `review` - Discovered operations that are not saved into API Shield Endpoint
                Management
              - `saved` - Discovered operations that are already saved into API Shield
                Endpoint Management
              - `ignored` - Discovered operations that have been marked as ignored

          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 zone_id:
            raise ValueError(f"Expected a non-empty value for `zone_id` but received {zone_id!r}")
        return self._get_api_list(
            path_template("/zones/{zone_id}/api_gateway/discovery/operations", zone_id=zone_id),
            page=SyncV4PagePaginationArray[DiscoveryOperation],
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "diff": diff,
                        "direction": direction,
                        "endpoint": endpoint,
                        "host": host,
                        "method": method,
                        "order": order,
                        "origin": origin,
                        "page": page,
                        "per_page": per_page,
                        "state": state,
                    },
                    operation_list_params.OperationListParams,
                ),
            ),
            model=DiscoveryOperation,
        )

    def bulk_edit(
        self,
        *,
        zone_id: str,
        body: Dict[str, operation_bulk_edit_params.Body],
        # 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,
    ) -> OperationBulkEditResponse:
        """
        Update the `state` on one or more discovered operations

        Args:
          zone_id: Identifier.

          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 zone_id:
            raise ValueError(f"Expected a non-empty value for `zone_id` but received {zone_id!r}")
        return self._patch(
            path_template("/zones/{zone_id}/api_gateway/discovery/operations", zone_id=zone_id),
            body=maybe_transform(body, operation_bulk_edit_params.OperationBulkEditParams),
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                post_parser=ResultWrapper[OperationBulkEditResponse]._unwrapper,
            ),
            cast_to=cast(Type[OperationBulkEditResponse], ResultWrapper[OperationBulkEditResponse]),
        )


class AsyncOperationsResource(AsyncAPIResource):
    @cached_property
    def with_raw_response(self) -> AsyncOperationsResourceWithRawResponse:
        """
        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/cloudflare/cloudflare-python#accessing-raw-response-data-eg-headers
        """
        return AsyncOperationsResourceWithRawResponse(self)

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

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

    def list(
        self,
        *,
        zone_id: str,
        diff: bool | Omit = omit,
        direction: Literal["asc", "desc"] | Omit = omit,
        endpoint: str | Omit = omit,
        host: SequenceNotStr[str] | Omit = omit,
        method: SequenceNotStr[str] | Omit = omit,
        order: Literal["host", "method", "endpoint", "traffic_stats.requests", "traffic_stats.last_updated"]
        | Omit = omit,
        origin: Literal["ML", "SessionIdentifier", "LabelDiscovery"] | Omit = omit,
        page: int | Omit = omit,
        per_page: int | Omit = omit,
        state: Literal["review", "saved", "ignored"] | 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,
    ) -> AsyncPaginator[DiscoveryOperation, AsyncV4PagePaginationArray[DiscoveryOperation]]:
        """
        Retrieve the most up to date view of discovered operations

        Args:
          zone_id: Identifier.

          diff: When `true`, only return API Discovery results that are not saved into API
              Shield Endpoint Management

          direction: Direction to order results.

          endpoint: Filter results to only include endpoints containing this pattern.

          host: Filter results to only include the specified hosts.

          method: Filter results to only include the specified HTTP methods.

          order: Field to order by

          origin: Filter results to only include discovery results sourced from a particular
              discovery engine

              - `ML` - Discovered operations that were sourced using ML API Discovery
              - `SessionIdentifier` - Discovered operations that were sourced using Session
                Identifier API Discovery

          page: Page number of paginated results.

          per_page: Maximum number of results per page.

          state: Filter results to only include discovery results in a particular state. States
              are as follows

              - `review` - Discovered operations that are not saved into API Shield Endpoint
                Management
              - `saved` - Discovered operations that are already saved into API Shield
                Endpoint Management
              - `ignored` - Discovered operations that have been marked as ignored

          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 zone_id:
            raise ValueError(f"Expected a non-empty value for `zone_id` but received {zone_id!r}")
        return self._get_api_list(
            path_template("/zones/{zone_id}/api_gateway/discovery/operations", zone_id=zone_id),
            page=AsyncV4PagePaginationArray[DiscoveryOperation],
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                query=maybe_transform(
                    {
                        "diff": diff,
                        "direction": direction,
                        "endpoint": endpoint,
                        "host": host,
                        "method": method,
                        "order": order,
                        "origin": origin,
                        "page": page,
                        "per_page": per_page,
                        "state": state,
                    },
                    operation_list_params.OperationListParams,
                ),
            ),
            model=DiscoveryOperation,
        )

    async def bulk_edit(
        self,
        *,
        zone_id: str,
        body: Dict[str, operation_bulk_edit_params.Body],
        # 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,
    ) -> OperationBulkEditResponse:
        """
        Update the `state` on one or more discovered operations

        Args:
          zone_id: Identifier.

          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 zone_id:
            raise ValueError(f"Expected a non-empty value for `zone_id` but received {zone_id!r}")
        return await self._patch(
            path_template("/zones/{zone_id}/api_gateway/discovery/operations", zone_id=zone_id),
            body=await async_maybe_transform(body, operation_bulk_edit_params.OperationBulkEditParams),
            options=make_request_options(
                extra_headers=extra_headers,
                extra_query=extra_query,
                extra_body=extra_body,
                timeout=timeout,
                post_parser=ResultWrapper[OperationBulkEditResponse]._unwrapper,
            ),
            cast_to=cast(Type[OperationBulkEditResponse], ResultWrapper[OperationBulkEditResponse]),
        )


class OperationsResourceWithRawResponse:
    def __init__(self, operations: OperationsResource) -> None:
        self._operations = operations

        self.list = to_raw_response_wrapper(
            operations.list,
        )
        self.bulk_edit = to_raw_response_wrapper(
            operations.bulk_edit,
        )


class AsyncOperationsResourceWithRawResponse:
    def __init__(self, operations: AsyncOperationsResource) -> None:
        self._operations = operations

        self.list = async_to_raw_response_wrapper(
            operations.list,
        )
        self.bulk_edit = async_to_raw_response_wrapper(
            operations.bulk_edit,
        )


class OperationsResourceWithStreamingResponse:
    def __init__(self, operations: OperationsResource) -> None:
        self._operations = operations

        self.list = to_streamed_response_wrapper(
            operations.list,
        )
        self.bulk_edit = to_streamed_response_wrapper(
            operations.bulk_edit,
        )


class AsyncOperationsResourceWithStreamingResponse:
    def __init__(self, operations: AsyncOperationsResource) -> None:
        self._operations = operations

        self.list = async_to_streamed_response_wrapper(
            operations.list,
        )
        self.bulk_edit = async_to_streamed_response_wrapper(
            operations.bulk_edit,
        )
