# pylint: disable=line-too-long,useless-suppression,too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from collections.abc import MutableMapping
from io import IOBase
import json
from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse

from azure.core import AsyncPipelineClient, MatchConditions
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceModifiedError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    StreamClosedError,
    StreamConsumedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling

from ... import models as _models
from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize
from ..._utils.serialization import Deserializer, Serializer
from ...operations._operations import (
    build_alerts_dismiss_request,
    build_alerts_get_request,
    build_alerts_list_external_request,
    build_alerts_list_request,
    build_benefit_recommendations_list_request,
    build_benefit_utilization_summaries_list_by_billing_account_id_request,
    build_benefit_utilization_summaries_list_by_billing_profile_id_request,
    build_benefit_utilization_summaries_list_by_savings_plan_id_request,
    build_benefit_utilization_summaries_list_by_savings_plan_order_request,
    build_budgets_create_or_update_request,
    build_budgets_delete_request,
    build_budgets_get_request,
    build_budgets_list_request,
    build_cost_allocation_rules_check_name_availability_request,
    build_cost_allocation_rules_create_or_update_request,
    build_cost_allocation_rules_delete_request,
    build_cost_allocation_rules_get_request,
    build_cost_allocation_rules_list_request,
    build_dimensions_by_external_cloud_provider_type_request,
    build_dimensions_list_request,
    build_exports_create_or_update_request,
    build_exports_delete_request,
    build_exports_execute_request,
    build_exports_get_execution_history_request,
    build_exports_get_request,
    build_exports_list_request,
    build_forecast_external_cloud_provider_usage_request,
    build_forecast_usage_request,
    build_generate_benefit_utilization_summaries_report_generate_by_billing_account_request,
    build_generate_benefit_utilization_summaries_report_generate_by_billing_profile_request,
    build_generate_benefit_utilization_summaries_report_generate_by_reservation_id_request,
    build_generate_benefit_utilization_summaries_report_generate_by_reservation_order_id_request,
    build_generate_benefit_utilization_summaries_report_generate_by_savings_plan_id_request,
    build_generate_benefit_utilization_summaries_report_generate_by_savings_plan_order_id_request,
    build_generate_cost_details_report_create_operation_request,
    build_generate_cost_details_report_get_operation_results_request,
    build_generate_detailed_cost_report_create_operation_request,
    build_generate_detailed_cost_report_operation_results_get_request,
    build_generate_detailed_cost_report_operation_status_get_request,
    build_generate_reservation_details_report_by_billing_account_id_request,
    build_generate_reservation_details_report_by_billing_profile_id_request,
    build_operations_list_request,
    build_price_sheet_download_by_billing_account_request,
    build_price_sheet_download_by_billing_profile_request,
    build_price_sheet_download_by_invoice_request,
    build_query_usage_by_external_cloud_provider_type_request,
    build_query_usage_request,
    build_scheduled_actions_check_name_availability_by_scope_request,
    build_scheduled_actions_check_name_availability_request,
    build_scheduled_actions_create_or_update_by_scope_request,
    build_scheduled_actions_create_or_update_request,
    build_scheduled_actions_delete_by_scope_request,
    build_scheduled_actions_delete_request,
    build_scheduled_actions_get_by_scope_request,
    build_scheduled_actions_get_request,
    build_scheduled_actions_list_by_scope_request,
    build_scheduled_actions_list_request,
    build_scheduled_actions_run_by_scope_request,
    build_scheduled_actions_run_request,
    build_settings_create_or_update_by_scope_request,
    build_settings_delete_by_scope_request,
    build_settings_get_by_scope_request,
    build_settings_list_request,
    build_views_create_or_update_by_scope_request,
    build_views_create_or_update_request,
    build_views_delete_by_scope_request,
    build_views_delete_request,
    build_views_get_by_scope_request,
    build_views_get_request,
    build_views_list_by_scope_request,
    build_views_list_request,
)
from .._configuration import CostManagementClientConfiguration

T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]]
JSON = MutableMapping[str, Any]
List = list


class GenerateDetailedCostReportOperationStatusOperations:  # pylint: disable=name-too-long
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`generate_detailed_cost_report_operation_status` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(
        self, operation_id: str, scope: str, **kwargs: Any
    ) -> _models.GenerateDetailedCostReportOperationStatuses:
        """Get the status of the specified operation. This link is provided in the
        GenerateDetailedCostReport creation request response header.

        :param operation_id: The target operation Id. Required.
        :type operation_id: str
        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :return: GenerateDetailedCostReportOperationStatuses. The
         GenerateDetailedCostReportOperationStatuses is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationStatuses
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GenerateDetailedCostReportOperationStatuses] = kwargs.pop("cls", None)

        _request = build_generate_detailed_cost_report_operation_status_get_request(
            operation_id=operation_id,
            scope=scope,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.GenerateDetailedCostReportOperationStatuses, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class Operations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`operations` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.CostManagementOperation"]:
        """List the operations for the provider.

        :return: An iterator like instance of CostManagementOperation
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.CostManagementOperation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.CostManagementOperation]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_operations_list_request(
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.CostManagementOperation],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BudgetsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`budgets` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, scope: str, budget_name: str, **kwargs: Any) -> _models.Budget:
        """Gets the budget for the scope by budget name.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param budget_name: Budget Name. Required.
        :type budget_name: str
        :return: Budget. The Budget is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Budget
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Budget] = kwargs.pop("cls", None)

        _request = build_budgets_get_request(
            scope=scope,
            budget_name=budget_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Budget, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        scope: str,
        budget_name: str,
        parameters: _models.Budget,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Budget:
        """The operation to create or update a budget. You can optionally provide an eTag if desired as a
        form of concurrency control. To obtain the latest eTag for a given budget, perform a get
        operation prior to your put operation.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param budget_name: Budget Name. Required.
        :type budget_name: str
        :param parameters: Parameters supplied to the Create Budget operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.Budget
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Budget. The Budget is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Budget
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self, scope: str, budget_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.Budget:
        """The operation to create or update a budget. You can optionally provide an eTag if desired as a
        form of concurrency control. To obtain the latest eTag for a given budget, perform a get
        operation prior to your put operation.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param budget_name: Budget Name. Required.
        :type budget_name: str
        :param parameters: Parameters supplied to the Create Budget operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Budget. The Budget is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Budget
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        scope: str,
        budget_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Budget:
        """The operation to create or update a budget. You can optionally provide an eTag if desired as a
        form of concurrency control. To obtain the latest eTag for a given budget, perform a get
        operation prior to your put operation.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param budget_name: Budget Name. Required.
        :type budget_name: str
        :param parameters: Parameters supplied to the Create Budget operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Budget. The Budget is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Budget
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self, scope: str, budget_name: str, parameters: Union[_models.Budget, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.Budget:
        """The operation to create or update a budget. You can optionally provide an eTag if desired as a
        form of concurrency control. To obtain the latest eTag for a given budget, perform a get
        operation prior to your put operation.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param budget_name: Budget Name. Required.
        :type budget_name: str
        :param parameters: Parameters supplied to the Create Budget operation. Is one of the following
         types: Budget, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.Budget or JSON or IO[bytes]
        :return: Budget. The Budget is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Budget
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Budget] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_budgets_create_or_update_request(
            scope=scope,
            budget_name=budget_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Budget, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(self, scope: str, budget_name: str, **kwargs: Any) -> None:
        """The operation to delete a budget.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param budget_name: Budget Name. Required.
        :type budget_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_budgets_delete_request(
            scope=scope,
            budget_name=budget_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list(self, scope: str, *, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.Budget"]:
        """Lists all budgets for the defined scope.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :keyword filter: OData filter option. May be used to filter budgets by properties/category. The
         filter supports 'eq' only. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Budget
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Budget]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Budget]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_budgets_list_request(
                    scope=scope,
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Budget],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class ExportsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`exports` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, scope: str, export_name: str, *, expand: Optional[str] = None, **kwargs: Any) -> _models.Export:
        """The operation to get the export for the defined scope by export name.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :keyword expand: May be used to expand the properties within an export. Currently only
         'runHistory' is supported and will return information for the last 10 runs of the export.
         Default value is None.
        :paramtype expand: str
        :return: Export. The Export is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Export
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Export] = kwargs.pop("cls", None)

        _request = build_exports_get_request(
            scope=scope,
            export_name=export_name,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Export, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        scope: str,
        export_name: str,
        parameters: _models.Export,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Export:
        """The operation to create or update a export. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.Export
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Export. The Export is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Export
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self, scope: str, export_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.Export:
        """The operation to create or update a export. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Export. The Export is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Export
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        scope: str,
        export_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Export:
        """The operation to create or update a export. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Export. The Export is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Export
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self, scope: str, export_name: str, parameters: Union[_models.Export, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.Export:
        """The operation to create or update a export. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate Export operation. Is one of the
         following types: Export, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.Export or JSON or IO[bytes]
        :return: Export. The Export is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Export
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Export] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_exports_create_or_update_request(
            scope=scope,
            export_name=export_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Export, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(self, scope: str, export_name: str, **kwargs: Any) -> None:
        """The operation to delete a export.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_exports_delete_request(
            scope=scope,
            export_name=export_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list(self, scope: str, *, expand: Optional[str] = None, **kwargs: Any) -> _models.ExportListResult:
        """The operation to list all exports at the given scope.

        :param scope: The scope associated with alerts operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :keyword expand: May be used to expand the properties within an export. Currently only
         'runHistory' is supported and will return information for the last run of each export. Default
         value is None.
        :paramtype expand: str
        :return: ExportListResult. The ExportListResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ExportListResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ExportListResult] = kwargs.pop("cls", None)

        _request = build_exports_list_request(
            scope=scope,
            expand=expand,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ExportListResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def execute(
        self,
        scope: str,
        export_name: str,
        parameters: Optional[_models.ExportRunRequest] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """The operation to run an export.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the Execute Export operation. Default value is None.
        :type parameters: ~azure.mgmt.costmanagement.models.ExportRunRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def execute(
        self,
        scope: str,
        export_name: str,
        parameters: Optional[JSON] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """The operation to run an export.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the Execute Export operation. Default value is None.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def execute(
        self,
        scope: str,
        export_name: str,
        parameters: Optional[IO[bytes]] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> None:
        """The operation to run an export.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the Execute Export operation. Default value is None.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def execute(
        self,
        scope: str,
        export_name: str,
        parameters: Optional[Union[_models.ExportRunRequest, JSON, IO[bytes]]] = None,
        **kwargs: Any
    ) -> None:
        """The operation to run an export.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :param parameters: Parameters supplied to the Execute Export operation. Is one of the following
         types: ExportRunRequest, JSON, IO[bytes] Default value is None.
        :type parameters: ~azure.mgmt.costmanagement.models.ExportRunRequest or JSON or IO[bytes]
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        content_type = content_type if parameters else None
        cls: ClsType[None] = kwargs.pop("cls", None)

        content_type = content_type or "application/json" if parameters else None
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            if parameters is not None:
                _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore
            else:
                _content = None

        _request = build_exports_execute_request(
            scope=scope,
            export_name=export_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def get_execution_history(
        self, scope: str, export_name: str, **kwargs: Any
    ) -> _models.ExportExecutionListResult:
        """The operation to get the run history of an export for the defined scope and export name.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param export_name: Export Name. Required.
        :type export_name: str
        :return: ExportExecutionListResult. The ExportExecutionListResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ExportExecutionListResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ExportExecutionListResult] = kwargs.pop("cls", None)

        _request = build_exports_get_execution_history_request(
            scope=scope,
            export_name=export_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ExportExecutionListResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class GenerateDetailedCostReportOperationResultsOperations:  # pylint: disable=name-too-long
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`generate_detailed_cost_report_operation_results` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _get_initial(self, operation_id: str, scope: str, **kwargs: Any) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_generate_detailed_cost_report_operation_results_get_request(
            operation_id=operation_id,
            scope=scope,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_get(
        self, operation_id: str, scope: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]:
        """Gets the result of the specified operation. The link with this operationId is provided as a
        response header of the initial request.

        :param operation_id: The target operation Id. Required.
        :type operation_id: str
        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :return: An instance of AsyncLROPoller that returns GenerateDetailedCostReportOperationResult.
         The GenerateDetailedCostReportOperationResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.GenerateDetailedCostReportOperationResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._get_initial(
                operation_id=operation_id,
                scope=scope,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.GenerateDetailedCostReportOperationResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class ViewsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`views` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, view_name: str, **kwargs: Any) -> _models.View:
        """Gets the view by view name.

        :param view_name: View name. Required.
        :type view_name: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.View] = kwargs.pop("cls", None)

        _request = build_views_get_request(
            view_name=view_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.View, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self, view_name: str, parameters: _models.View, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.View
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self, view_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self, view_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self, view_name: str, parameters: Union[_models.View, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is one of the
         following types: View, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.View or JSON or IO[bytes]
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.View] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_views_create_or_update_request(
            view_name=view_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.View, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(self, view_name: str, **kwargs: Any) -> None:
        """The operation to delete a view.

        :param view_name: View name. Required.
        :type view_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_views_delete_request(
            view_name=view_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.View"]:
        """Lists all views by tenant and object.

        :return: An iterator like instance of View
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.View]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_views_list_request(
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.View],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> _models.View:
        """Gets the view for the defined scope by view name.

        :param scope: undefined. Required.
        :type scope: str
        :param view_name: View name. Required.
        :type view_name: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.View] = kwargs.pop("cls", None)

        _request = build_views_get_by_scope_request(
            scope=scope,
            view_name=view_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.View, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        view_name: str,
        parameters: _models.View,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: undefined. Required.
        :type scope: str
        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.View
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_by_scope(
        self, scope: str, view_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: undefined. Required.
        :type scope: str
        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        view_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: undefined. Required.
        :type scope: str
        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update_by_scope(
        self, scope: str, view_name: str, parameters: Union[_models.View, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.View:
        """The operation to create or update a view. Update operation requires latest eTag to be set in
        the request. You may obtain the latest eTag by performing a get operation. Create operation
        does not require eTag.

        :param scope: undefined. Required.
        :type scope: str
        :param view_name: View name. Required.
        :type view_name: str
        :param parameters: Parameters supplied to the CreateOrUpdate View operation. Is one of the
         following types: View, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.View or JSON or IO[bytes]
        :return: View. The View is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.View
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.View] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_views_create_or_update_by_scope_request(
            scope=scope,
            view_name=view_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.View, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_by_scope(self, scope: str, view_name: str, **kwargs: Any) -> None:
        """The operation to delete a view.

        :param scope: undefined. Required.
        :type scope: str
        :param view_name: View name. Required.
        :type view_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_views_delete_by_scope_request(
            scope=scope,
            view_name=view_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_scope(self, scope: str, **kwargs: Any) -> AsyncItemPaged["_models.View"]:
        """Lists all views at the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :return: An iterator like instance of View
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.View]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.View]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_views_list_by_scope_request(
                    scope=scope,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.View],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class AlertsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`alerts` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert:
        """Gets the alert for the scope by alert ID.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param alert_id: Alert ID. Required.
        :type alert_id: str
        :return: Alert. The Alert is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Alert
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Alert] = kwargs.pop("cls", None)

        _request = build_alerts_get_request(
            scope=scope,
            alert_id=alert_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Alert, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def dismiss(
        self,
        scope: str,
        alert_id: str,
        parameters: _models.DismissAlertPayload,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Alert:
        """Dismisses the specified alert.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param alert_id: Alert ID. Required.
        :type alert_id: str
        :param parameters: Parameters supplied to the Dismiss Alert operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Alert. The Alert is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Alert
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def dismiss(
        self, scope: str, alert_id: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.Alert:
        """Dismisses the specified alert.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param alert_id: Alert ID. Required.
        :type alert_id: str
        :param parameters: Parameters supplied to the Dismiss Alert operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Alert. The Alert is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Alert
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def dismiss(
        self, scope: str, alert_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.Alert:
        """Dismisses the specified alert.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param alert_id: Alert ID. Required.
        :type alert_id: str
        :param parameters: Parameters supplied to the Dismiss Alert operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Alert. The Alert is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Alert
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def dismiss(
        self, scope: str, alert_id: str, parameters: Union[_models.DismissAlertPayload, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.Alert:
        """Dismisses the specified alert.

        :param scope: The fully qualified Azure Resource manager identifier of the resource. Required.
        :type scope: str
        :param alert_id: Alert ID. Required.
        :type alert_id: str
        :param parameters: Parameters supplied to the Dismiss Alert operation. Is one of the following
         types: DismissAlertPayload, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.DismissAlertPayload or JSON or IO[bytes]
        :return: Alert. The Alert is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Alert
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Alert] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_alerts_dismiss_request(
            scope=scope,
            alert_id=alert_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Alert, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list(self, scope: str, **kwargs: Any) -> _models.AlertsResult:
        """Lists the alerts for scope defined.

        :param scope: The scope associated with alerts operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :return: AlertsResult. The AlertsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.AlertsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AlertsResult] = kwargs.pop("cls", None)

        _request = build_alerts_list_request(
            scope=scope,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AlertsResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_external(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        **kwargs: Any
    ) -> _models.AlertsResult:
        """Lists the Alerts for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :return: AlertsResult. The AlertsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.AlertsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.AlertsResult] = kwargs.pop("cls", None)

        _request = build_alerts_list_external_request(
            external_cloud_provider_type=external_cloud_provider_type,
            external_cloud_provider_id=external_cloud_provider_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.AlertsResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class ScheduledActionsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`scheduled_actions` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, name: str, **kwargs: Any) -> _models.ScheduledAction:
        """Get the private scheduled action by name.

        :param name: Scheduled action name. Required.
        :type name: str
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None)

        _request = build_scheduled_actions_get_request(
            name=name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ScheduledAction, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        name: str,
        scheduled_action: _models.ScheduledAction,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a private scheduled action.

        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Required.
        :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        name: str,
        scheduled_action: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a private scheduled action.

        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Required.
        :type scheduled_action: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        name: str,
        scheduled_action: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a private scheduled action.

        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Required.
        :type scheduled_action: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        name: str,
        scheduled_action: Union[_models.ScheduledAction, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a private scheduled action.

        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Is one of the following
         types: ScheduledAction, JSON, IO[bytes] Required.
        :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(scheduled_action, (IOBase, bytes)):
            _content = scheduled_action
        else:
            _content = json.dumps(scheduled_action, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_scheduled_actions_create_or_update_request(
            name=name,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ScheduledAction, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(self, name: str, **kwargs: Any) -> None:
        """Delete a private scheduled action.

        :param name: Scheduled action name. Required.
        :type name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_scheduled_actions_delete_request(
            name=name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list(self, *, filter: Optional[str] = None, **kwargs: Any) -> AsyncItemPaged["_models.ScheduledAction"]:
        """List all private scheduled actions.

        :keyword filter: May be used to filter scheduled actions by properties/viewId. Supported
         operator is 'eq'. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of ScheduledAction
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ScheduledAction]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_scheduled_actions_list_request(
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ScheduledAction],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponseWithNestedDetails,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def run(self, name: str, **kwargs: Any) -> None:
        """Processes a private scheduled action.

        :param name: Scheduled action name. Required.
        :type name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_scheduled_actions_run_request(
            name=name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def get_by_scope(self, scope: str, name: str, **kwargs: Any) -> _models.ScheduledAction:
        """Get the shared scheduled action from the given scope by name.

        :param scope: undefined. Required.
        :type scope: str
        :param name: Scheduled action name. Required.
        :type name: str
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None)

        _request = build_scheduled_actions_get_by_scope_request(
            scope=scope,
            name=name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ScheduledAction, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        name: str,
        scheduled_action: _models.ScheduledAction,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a shared scheduled action within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Required.
        :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        name: str,
        scheduled_action: JSON,
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a shared scheduled action within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Required.
        :type scheduled_action: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        name: str,
        scheduled_action: IO[bytes],
        *,
        content_type: str = "application/json",
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a shared scheduled action within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Required.
        :type scheduled_action: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update_by_scope(
        self,
        scope: str,
        name: str,
        scheduled_action: Union[_models.ScheduledAction, JSON, IO[bytes]],
        *,
        etag: Optional[str] = None,
        match_condition: Optional[MatchConditions] = None,
        **kwargs: Any
    ) -> _models.ScheduledAction:
        """Create or update a shared scheduled action within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param name: Scheduled action name. Required.
        :type name: str
        :param scheduled_action: Scheduled action to be created or updated. Is one of the following
         types: ScheduledAction, JSON, IO[bytes] Required.
        :type scheduled_action: ~azure.mgmt.costmanagement.models.ScheduledAction or JSON or IO[bytes]
        :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
         None.
        :paramtype etag: str
        :keyword match_condition: The match condition to use upon the etag. Default value is None.
        :paramtype match_condition: ~azure.core.MatchConditions
        :return: ScheduledAction. The ScheduledAction is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ScheduledAction
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        if match_condition == MatchConditions.IfNotModified:
            error_map[412] = ResourceModifiedError
        elif match_condition == MatchConditions.IfPresent:
            error_map[412] = ResourceNotFoundError
        elif match_condition == MatchConditions.IfMissing:
            error_map[412] = ResourceExistsError
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ScheduledAction] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(scheduled_action, (IOBase, bytes)):
            _content = scheduled_action
        else:
            _content = json.dumps(scheduled_action, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_scheduled_actions_create_or_update_by_scope_request(
            scope=scope,
            name=name,
            etag=etag,
            match_condition=match_condition,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ScheduledAction, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_by_scope(self, scope: str, name: str, **kwargs: Any) -> None:
        """Delete a scheduled action within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param name: Scheduled action name. Required.
        :type name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_scheduled_actions_delete_by_scope_request(
            scope=scope,
            name=name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list_by_scope(
        self, scope: str, *, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.ScheduledAction"]:
        """List all shared scheduled actions within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :keyword filter: May be used to filter scheduled actions by properties/viewId. Supported
         operator is 'eq'. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of ScheduledAction
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.ScheduledAction]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ScheduledAction]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_scheduled_actions_list_by_scope_request(
                    scope=scope,
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ScheduledAction],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponseWithNestedDetails,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def run_by_scope(self, scope: str, name: str, **kwargs: Any) -> None:
        """Runs a shared scheduled action within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param name: Scheduled action name. Required.
        :type name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_scheduled_actions_run_by_scope_request(
            scope=scope,
            name=name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @overload
    async def check_name_availability(
        self,
        check_name_availability_request: _models.CheckNameAvailabilityRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action.

        :param check_name_availability_request: The request body. Required.
        :type check_name_availability_request:
         ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self, check_name_availability_request: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action.

        :param check_name_availability_request: The request body. Required.
        :type check_name_availability_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self, check_name_availability_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action.

        :param check_name_availability_request: The request body. Required.
        :type check_name_availability_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_name_availability(
        self,
        check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action.

        :param check_name_availability_request: The request body. Is one of the following types:
         CheckNameAvailabilityRequest, JSON, IO[bytes] Required.
        :type check_name_availability_request:
         ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or JSON or IO[bytes]
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CheckNameAvailabilityResponse] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(check_name_availability_request, (IOBase, bytes)):
            _content = check_name_availability_request
        else:
            _content = json.dumps(check_name_availability_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_scheduled_actions_check_name_availability_request(
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CheckNameAvailabilityResponse, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def check_name_availability_by_scope(
        self,
        scope: str,
        check_name_availability_request: _models.CheckNameAvailabilityRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action within the given scope.

        :param scope: The scope associated with scheduled action operations. This includes
         'subscriptions/{subscriptionId}' for subscription scope,
         'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
         Department scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for BillingProfile scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
         for InvoiceSection scope,
         'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for
         External Billing Account scope and
         'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for
         External Subscription scope. Note: Insight Alerts are only available on subscription scope.
         Required.
        :type scope: str
        :param check_name_availability_request: Scheduled action to be created or updated. Required.
        :type check_name_availability_request:
         ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability_by_scope(
        self,
        scope: str,
        check_name_availability_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action within the given scope.

        :param scope: The scope associated with scheduled action operations. This includes
         'subscriptions/{subscriptionId}' for subscription scope,
         'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
         Department scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for BillingProfile scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
         for InvoiceSection scope,
         'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for
         External Billing Account scope and
         'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for
         External Subscription scope. Note: Insight Alerts are only available on subscription scope.
         Required.
        :type scope: str
        :param check_name_availability_request: Scheduled action to be created or updated. Required.
        :type check_name_availability_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability_by_scope(
        self,
        scope: str,
        check_name_availability_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action within the given scope.

        :param scope: The scope associated with scheduled action operations. This includes
         'subscriptions/{subscriptionId}' for subscription scope,
         'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
         Department scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for BillingProfile scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
         for InvoiceSection scope,
         'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for
         External Billing Account scope and
         'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for
         External Subscription scope. Note: Insight Alerts are only available on subscription scope.
         Required.
        :type scope: str
        :param check_name_availability_request: Scheduled action to be created or updated. Required.
        :type check_name_availability_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_name_availability_by_scope(
        self,
        scope: str,
        check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResponse:
        """Checks availability and correctness of the name for a scheduled action within the given scope.

        :param scope: The scope associated with scheduled action operations. This includes
         'subscriptions/{subscriptionId}' for subscription scope,
         'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}' for
         Department scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for BillingProfile scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/invoiceSections/{invoiceSectionId}'
         for InvoiceSection scope,
         'providers/Microsoft.CostManagement/externalBillingAccounts/{externalBillingAccountName}' for
         External Billing Account scope and
         'providers/Microsoft.CostManagement/externalSubscriptions/{externalSubscriptionName}' for
         External Subscription scope. Note: Insight Alerts are only available on subscription scope.
         Required.
        :type scope: str
        :param check_name_availability_request: Scheduled action to be created or updated. Is one of
         the following types: CheckNameAvailabilityRequest, JSON, IO[bytes] Required.
        :type check_name_availability_request:
         ~azure.mgmt.costmanagement.models.CheckNameAvailabilityRequest or JSON or IO[bytes]
        :return: CheckNameAvailabilityResponse. The CheckNameAvailabilityResponse is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CheckNameAvailabilityResponse] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(check_name_availability_request, (IOBase, bytes)):
            _content = check_name_availability_request
        else:
            _content = json.dumps(check_name_availability_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_scheduled_actions_check_name_availability_by_scope_request(
            scope=scope,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponseWithNestedDetails,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CheckNameAvailabilityResponse, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class SettingsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`settings` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get_by_scope(self, scope: str, type: Union[str, _models.SettingType], **kwargs: Any) -> _models.Setting:
        """Get the setting from the given scope by name.

        :param scope: undefined. Required.
        :type scope: str
        :param type: Setting type. "taginheritance" Required.
        :type type: str or ~azure.mgmt.costmanagement.models.SettingType
        :return: Setting. The Setting is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Setting
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.Setting] = kwargs.pop("cls", None)

        _request = build_settings_get_by_scope_request(
            scope=scope,
            type=type,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Setting, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        type: Union[str, _models.SettingType],
        setting: _models.Setting,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Setting:
        """Create or update a setting within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param type: Setting type. "taginheritance" Required.
        :type type: str or ~azure.mgmt.costmanagement.models.SettingType
        :param setting: Setting to be created or updated. Required.
        :type setting: ~azure.mgmt.costmanagement.models.Setting
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Setting. The Setting is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Setting
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        type: Union[str, _models.SettingType],
        setting: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Setting:
        """Create or update a setting within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param type: Setting type. "taginheritance" Required.
        :type type: str or ~azure.mgmt.costmanagement.models.SettingType
        :param setting: Setting to be created or updated. Required.
        :type setting: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Setting. The Setting is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Setting
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_by_scope(
        self,
        scope: str,
        type: Union[str, _models.SettingType],
        setting: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Setting:
        """Create or update a setting within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param type: Setting type. "taginheritance" Required.
        :type type: str or ~azure.mgmt.costmanagement.models.SettingType
        :param setting: Setting to be created or updated. Required.
        :type setting: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Setting. The Setting is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Setting
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update_by_scope(
        self,
        scope: str,
        type: Union[str, _models.SettingType],
        setting: Union[_models.Setting, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.Setting:
        """Create or update a setting within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param type: Setting type. "taginheritance" Required.
        :type type: str or ~azure.mgmt.costmanagement.models.SettingType
        :param setting: Setting to be created or updated. Is one of the following types: Setting, JSON,
         IO[bytes] Required.
        :type setting: ~azure.mgmt.costmanagement.models.Setting or JSON or IO[bytes]
        :return: Setting. The Setting is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.Setting
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Setting] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(setting, (IOBase, bytes)):
            _content = setting
        else:
            _content = json.dumps(setting, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_settings_create_or_update_by_scope_request(
            scope=scope,
            type=type,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.Setting, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_by_scope(self, scope: str, type: Union[str, _models.SettingType], **kwargs: Any) -> None:
        """Delete a setting within the given scope.

        :param scope: undefined. Required.
        :type scope: str
        :param type: Setting type. "taginheritance" Required.
        :type type: str or ~azure.mgmt.costmanagement.models.SettingType
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_settings_delete_by_scope_request(
            scope=scope,
            type=type,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace_async
    async def list(self, scope: str, **kwargs: Any) -> _models.SettingsListResult:
        """List all cost management settings in the requested scope.

        :param scope: undefined. Required.
        :type scope: str
        :return: SettingsListResult. The SettingsListResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.SettingsListResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.SettingsListResult] = kwargs.pop("cls", None)

        _request = build_settings_list_request(
            scope=scope,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SettingsListResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class GenerateCostDetailsReportOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`generate_cost_details_report` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _get_operation_results_initial(
        self, scope: str, operation_id: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_generate_cost_details_report_get_operation_results_request(
            scope=scope,
            operation_id=operation_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_get_operation_results(
        self, scope: str, operation_id: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.CostDetailsOperationResults]:
        """Get the result of the specified operation. This link is provided in the CostDetails creation
        request response Location header.

        :param scope: The ARM Resource ID for subscription, billing account, or other billing
         scopes.Currently Resource Group and Management Group are not supported. For details, see
         `https://aka.ms/costmgmt/scopes <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param operation_id: The target operation Id. Required.
        :type operation_id: str
        :return: An instance of AsyncLROPoller that returns CostDetailsOperationResults. The
         CostDetailsOperationResults is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CostDetailsOperationResults] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._get_operation_results_initial(
                scope=scope,
                operation_id=operation_id,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.CostDetailsOperationResults, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.CostDetailsOperationResults].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.CostDetailsOperationResults](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _create_operation_initial(
        self,
        scope: str,
        parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_cost_details_report_create_operation_request(
            scope=scope,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.GenerateCostDetailsReportErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_operation(
        self,
        scope: str,
        parameters: _models.GenerateCostDetailsReportRequestDefinition,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CostDetailsOperationResults]:
        """This API is the replacement for all previously release Usage Details APIs. Request to generate
        a cost details report for the provided date range, billing period (Only enterprise customers)
        or Invoice Id asynchronously at a certain scope. The initial call to request a report will
        return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the
        endpoint to poll to get the result of the report generation. The 'Retry-After' provides the
        duration to wait before polling for the generated report. A call to poll the report operation
        will provide a 202 response with a 'Location' header if the operation is still in progress.
        Once the report generation operation completes, the polling endpoint will provide a 200
        response along with details on the report blob(s) that are available for download. The details
        on the file(s) available for download will be available in the polling response body. To
        Understand cost details (formerly known as usage details) fields found in files ,see
        `https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields
        <https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields>`_.

        :param scope: The ARM Resource ID for subscription, billing account, or other billing
         scopes.Currently Resource Group and Management Group are not supported. For details, see
         `https://aka.ms/costmgmt/scopes <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create cost details operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CostDetailsOperationResults. The
         CostDetailsOperationResults is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_operation(
        self, scope: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.CostDetailsOperationResults]:
        """This API is the replacement for all previously release Usage Details APIs. Request to generate
        a cost details report for the provided date range, billing period (Only enterprise customers)
        or Invoice Id asynchronously at a certain scope. The initial call to request a report will
        return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the
        endpoint to poll to get the result of the report generation. The 'Retry-After' provides the
        duration to wait before polling for the generated report. A call to poll the report operation
        will provide a 202 response with a 'Location' header if the operation is still in progress.
        Once the report generation operation completes, the polling endpoint will provide a 200
        response along with details on the report blob(s) that are available for download. The details
        on the file(s) available for download will be available in the polling response body. To
        Understand cost details (formerly known as usage details) fields found in files ,see
        `https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields
        <https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields>`_.

        :param scope: The ARM Resource ID for subscription, billing account, or other billing
         scopes.Currently Resource Group and Management Group are not supported. For details, see
         `https://aka.ms/costmgmt/scopes <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create cost details operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CostDetailsOperationResults. The
         CostDetailsOperationResults is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_operation(
        self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.CostDetailsOperationResults]:
        """This API is the replacement for all previously release Usage Details APIs. Request to generate
        a cost details report for the provided date range, billing period (Only enterprise customers)
        or Invoice Id asynchronously at a certain scope. The initial call to request a report will
        return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the
        endpoint to poll to get the result of the report generation. The 'Retry-After' provides the
        duration to wait before polling for the generated report. A call to poll the report operation
        will provide a 202 response with a 'Location' header if the operation is still in progress.
        Once the report generation operation completes, the polling endpoint will provide a 200
        response along with details on the report blob(s) that are available for download. The details
        on the file(s) available for download will be available in the polling response body. To
        Understand cost details (formerly known as usage details) fields found in files ,see
        `https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields
        <https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields>`_.

        :param scope: The ARM Resource ID for subscription, billing account, or other billing
         scopes.Currently Resource Group and Management Group are not supported. For details, see
         `https://aka.ms/costmgmt/scopes <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create cost details operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns CostDetailsOperationResults. The
         CostDetailsOperationResults is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_operation(
        self,
        scope: str,
        parameters: Union[_models.GenerateCostDetailsReportRequestDefinition, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.CostDetailsOperationResults]:
        """This API is the replacement for all previously release Usage Details APIs. Request to generate
        a cost details report for the provided date range, billing period (Only enterprise customers)
        or Invoice Id asynchronously at a certain scope. The initial call to request a report will
        return a 202 with a 'Location' and 'Retry-After' header. The 'Location' header will provide the
        endpoint to poll to get the result of the report generation. The 'Retry-After' provides the
        duration to wait before polling for the generated report. A call to poll the report operation
        will provide a 202 response with a 'Location' header if the operation is still in progress.
        Once the report generation operation completes, the polling endpoint will provide a 200
        response along with details on the report blob(s) that are available for download. The details
        on the file(s) available for download will be available in the polling response body. To
        Understand cost details (formerly known as usage details) fields found in files ,see
        `https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields
        <https://learn.microsoft.com/en-us/azure/cost-management-billing/automate/understand-usage-details-fields>`_.

        :param scope: The ARM Resource ID for subscription, billing account, or other billing
         scopes.Currently Resource Group and Management Group are not supported. For details, see
         `https://aka.ms/costmgmt/scopes <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create cost details operation. Is one of the
         following types: GenerateCostDetailsReportRequestDefinition, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.GenerateCostDetailsReportRequestDefinition
         or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns CostDetailsOperationResults. The
         CostDetailsOperationResults is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.CostDetailsOperationResults]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CostDetailsOperationResults] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_operation_initial(
                scope=scope,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.CostDetailsOperationResults, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.CostDetailsOperationResults].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.CostDetailsOperationResults](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class CostAllocationRulesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`cost_allocation_rules` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def get(self, billing_account_id: str, rule_name: str, **kwargs: Any) -> _models.CostAllocationRuleDefinition:
        """Get a cost allocation rule by rule name and billing account or enterprise enrollment.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param rule_name: Cost allocation rule name. The name cannot include spaces or any non
         alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required.
        :type rule_name: str
        :return: CostAllocationRuleDefinition. The CostAllocationRuleDefinition is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.CostAllocationRuleDefinition] = kwargs.pop("cls", None)

        _request = build_cost_allocation_rules_get_request(
            billing_account_id=billing_account_id,
            rule_name=rule_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CostAllocationRuleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        billing_account_id: str,
        rule_name: str,
        cost_allocation_rule: _models.CostAllocationRuleDefinition,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CostAllocationRuleDefinition:
        """Create/Update a rule to allocate cost between different resources within a billing account or
        enterprise enrollment.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param rule_name: Cost allocation rule name. The name cannot include spaces or any non
         alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required.
        :type rule_name: str
        :param cost_allocation_rule: Cost allocation rule to be created or updated. Required.
        :type cost_allocation_rule: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CostAllocationRuleDefinition. The CostAllocationRuleDefinition is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        billing_account_id: str,
        rule_name: str,
        cost_allocation_rule: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CostAllocationRuleDefinition:
        """Create/Update a rule to allocate cost between different resources within a billing account or
        enterprise enrollment.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param rule_name: Cost allocation rule name. The name cannot include spaces or any non
         alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required.
        :type rule_name: str
        :param cost_allocation_rule: Cost allocation rule to be created or updated. Required.
        :type cost_allocation_rule: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CostAllocationRuleDefinition. The CostAllocationRuleDefinition is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        billing_account_id: str,
        rule_name: str,
        cost_allocation_rule: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CostAllocationRuleDefinition:
        """Create/Update a rule to allocate cost between different resources within a billing account or
        enterprise enrollment.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param rule_name: Cost allocation rule name. The name cannot include spaces or any non
         alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required.
        :type rule_name: str
        :param cost_allocation_rule: Cost allocation rule to be created or updated. Required.
        :type cost_allocation_rule: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CostAllocationRuleDefinition. The CostAllocationRuleDefinition is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        billing_account_id: str,
        rule_name: str,
        cost_allocation_rule: Union[_models.CostAllocationRuleDefinition, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.CostAllocationRuleDefinition:
        """Create/Update a rule to allocate cost between different resources within a billing account or
        enterprise enrollment.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param rule_name: Cost allocation rule name. The name cannot include spaces or any non
         alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required.
        :type rule_name: str
        :param cost_allocation_rule: Cost allocation rule to be created or updated. Is one of the
         following types: CostAllocationRuleDefinition, JSON, IO[bytes] Required.
        :type cost_allocation_rule: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition or
         JSON or IO[bytes]
        :return: CostAllocationRuleDefinition. The CostAllocationRuleDefinition is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CostAllocationRuleDefinition] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(cost_allocation_rule, (IOBase, bytes)):
            _content = cost_allocation_rule
        else:
            _content = json.dumps(cost_allocation_rule, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_cost_allocation_rules_create_or_update_request(
            billing_account_id=billing_account_id,
            rule_name=rule_name,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CostAllocationRuleDefinition, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(self, billing_account_id: str, rule_name: str, **kwargs: Any) -> None:
        """Delete cost allocation rule for billing account or enterprise enrollment.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param rule_name: Cost allocation rule name. The name cannot include spaces or any non
         alphanumeric characters other than '_' and '-'. The max length is 260 characters. Required.
        :type rule_name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_cost_allocation_rules_delete_request(
            billing_account_id=billing_account_id,
            rule_name=rule_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def list(self, billing_account_id: str, **kwargs: Any) -> AsyncItemPaged["_models.CostAllocationRuleDefinition"]:
        """Get the list of all cost allocation rules for a billing account or enterprise enrollment.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :return: An iterator like instance of CostAllocationRuleDefinition
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.CostAllocationRuleDefinition]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.CostAllocationRuleDefinition]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_cost_allocation_rules_list_request(
                    billing_account_id=billing_account_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.CostAllocationRuleDefinition],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def check_name_availability(
        self,
        billing_account_id: str,
        cost_allocation_rule_check_name_availability_request: _models.CostAllocationRuleCheckNameAvailabilityRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse:
        """Checks availability and correctness of a name for a cost allocation rule.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created
         or updated. Required.
        :type cost_allocation_rule_check_name_availability_request:
         ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CostAllocationRuleCheckNameAvailabilityResponse. The
         CostAllocationRuleCheckNameAvailabilityResponse is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self,
        billing_account_id: str,
        cost_allocation_rule_check_name_availability_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse:
        """Checks availability and correctness of a name for a cost allocation rule.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created
         or updated. Required.
        :type cost_allocation_rule_check_name_availability_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CostAllocationRuleCheckNameAvailabilityResponse. The
         CostAllocationRuleCheckNameAvailabilityResponse is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self,
        billing_account_id: str,
        cost_allocation_rule_check_name_availability_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse:
        """Checks availability and correctness of a name for a cost allocation rule.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created
         or updated. Required.
        :type cost_allocation_rule_check_name_availability_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CostAllocationRuleCheckNameAvailabilityResponse. The
         CostAllocationRuleCheckNameAvailabilityResponse is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_name_availability(
        self,
        billing_account_id: str,
        cost_allocation_rule_check_name_availability_request: Union[
            _models.CostAllocationRuleCheckNameAvailabilityRequest, JSON, IO[bytes]
        ],
        **kwargs: Any
    ) -> _models.CostAllocationRuleCheckNameAvailabilityResponse:
        """Checks availability and correctness of a name for a cost allocation rule.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param cost_allocation_rule_check_name_availability_request: Cost allocation rule to be created
         or updated. Is one of the following types: CostAllocationRuleCheckNameAvailabilityRequest,
         JSON, IO[bytes] Required.
        :type cost_allocation_rule_check_name_availability_request:
         ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityRequest or JSON or
         IO[bytes]
        :return: CostAllocationRuleCheckNameAvailabilityResponse. The
         CostAllocationRuleCheckNameAvailabilityResponse is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.CostAllocationRuleCheckNameAvailabilityResponse
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CostAllocationRuleCheckNameAvailabilityResponse] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(cost_allocation_rule_check_name_availability_request, (IOBase, bytes)):
            _content = cost_allocation_rule_check_name_availability_request
        else:
            _content = json.dumps(cost_allocation_rule_check_name_availability_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_cost_allocation_rules_check_name_availability_request(
            billing_account_id=billing_account_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CostAllocationRuleCheckNameAvailabilityResponse, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class BenefitRecommendationsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`benefit_recommendations` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        billing_scope: str,
        *,
        filter: Optional[str] = None,
        orderby: Optional[str] = None,
        expand: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BenefitRecommendationModel"]:
        """List of recommendations for purchasing savings plan.

        :param billing_scope: The scope associated with benefit recommendation operations. This
         includes '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resource group scope,
         /providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for enterprise agreement
         scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billing profile scope. Required.
        :type billing_scope: str
        :keyword filter: Can be used to filter benefitRecommendations by: properties/scope with allowed
         values ['Single', 'Shared'] and default value 'Shared'; and properties/lookBackPeriod with
         allowed values ['Last7Days', 'Last30Days', 'Last60Days'] and default value 'Last60Days';
         properties/term with allowed values ['P1Y', 'P3Y'] and default value 'P3Y';
         properties/subscriptionId; properties/resourceGroup. Default value is None.
        :paramtype filter: str
        :keyword orderby: May be used to order the recommendations by: properties/armSkuName. For the
         savings plan, the results are in order by default. There is no need to use this clause. Default
         value is None.
        :paramtype orderby: str
        :keyword expand: May be used to expand the properties by: properties/usage,
         properties/allRecommendationDetails. Default value is None.
        :paramtype expand: str
        :return: An iterator like instance of BenefitRecommendationModel
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitRecommendationModel]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BenefitRecommendationModel]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_benefit_recommendations_list_request(
                    billing_scope=billing_scope,
                    filter=filter,
                    orderby=orderby,
                    expand=expand,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BenefitRecommendationModel],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class BenefitUtilizationSummariesOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`benefit_utilization_summaries` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list_by_billing_account_id(
        self,
        billing_account_id: str,
        *,
        grain_parameter: Optional[Union[str, _models.GrainParameter]] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BenefitUtilizationSummary"]:
        """Lists savings plan utilization summaries for the enterprise agreement scope. Supported at grain
        values: 'Daily' and 'Monthly'.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :keyword grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default
         value is None.
        :paramtype grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter
        :keyword filter: Supports filtering by properties/benefitId, properties/benefitOrderId and
         properties/usageDate. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of BenefitUtilizationSummary
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BenefitUtilizationSummary]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_benefit_utilization_summaries_list_by_billing_account_id_request(
                    billing_account_id=billing_account_id,
                    grain_parameter=grain_parameter,
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BenefitUtilizationSummary],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_billing_profile_id(
        self,
        billing_account_id: str,
        billing_profile_id: str,
        *,
        grain_parameter: Optional[Union[str, _models.GrainParameter]] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BenefitUtilizationSummary"]:
        """Lists savings plan utilization summaries for billing profile. Supported at grain values:
        'Daily' and 'Monthly'.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param billing_profile_id: Billing Profile ID. Required.
        :type billing_profile_id: str
        :keyword grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default
         value is None.
        :paramtype grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter
        :keyword filter: Supports filtering by properties/benefitId, properties/benefitOrderId and
         properties/usageDate. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of BenefitUtilizationSummary
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BenefitUtilizationSummary]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_benefit_utilization_summaries_list_by_billing_profile_id_request(
                    billing_account_id=billing_account_id,
                    billing_profile_id=billing_profile_id,
                    grain_parameter=grain_parameter,
                    filter=filter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BenefitUtilizationSummary],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_savings_plan_order(
        self,
        savings_plan_order_id: str,
        *,
        filter: Optional[str] = None,
        grain_parameter: Optional[Union[str, _models.GrainParameter]] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BenefitUtilizationSummary"]:
        """Lists the savings plan utilization summaries for daily or monthly grain.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :keyword filter: Supports filtering by properties/usageDate. Default value is None.
        :paramtype filter: str
        :keyword grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default
         value is None.
        :paramtype grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter
        :return: An iterator like instance of BenefitUtilizationSummary
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BenefitUtilizationSummary]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_benefit_utilization_summaries_list_by_savings_plan_order_request(
                    savings_plan_order_id=savings_plan_order_id,
                    filter=filter,
                    grain_parameter=grain_parameter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BenefitUtilizationSummary],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_by_savings_plan_id(
        self,
        savings_plan_order_id: str,
        savings_plan_id: str,
        *,
        filter: Optional[str] = None,
        grain_parameter: Optional[Union[str, _models.GrainParameter]] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.BenefitUtilizationSummary"]:
        """Lists the savings plan utilization summaries for daily or monthly grain.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: Savings plan ID. Required.
        :type savings_plan_id: str
        :keyword filter: Supports filtering by properties/usageDate. Default value is None.
        :paramtype filter: str
        :keyword grain_parameter: Grain. Known values are: "Hourly", "Daily", and "Monthly". Default
         value is None.
        :paramtype grain_parameter: str or ~azure.mgmt.costmanagement.models.GrainParameter
        :return: An iterator like instance of BenefitUtilizationSummary
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.BenefitUtilizationSummary]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.BenefitUtilizationSummary]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_benefit_utilization_summaries_list_by_savings_plan_id_request(
                    savings_plan_order_id=savings_plan_order_id,
                    savings_plan_id=savings_plan_id,
                    filter=filter,
                    grain_parameter=grain_parameter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.BenefitUtilizationSummary],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class GenerateBenefitUtilizationSummariesReportOperations:  # pylint: disable=name-too-long
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`generate_benefit_utilization_summaries_report` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _generate_by_billing_account_initial(
        self,
        billing_account_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)):
            _content = benefit_utilization_summaries_request
        else:
            _content = json.dumps(benefit_utilization_summaries_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_benefit_utilization_summaries_report_generate_by_billing_account_request(
            billing_account_id=billing_account_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ArmErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_generate_by_billing_account(
        self,
        billing_account_id: str,
        benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account.
        This API supports only enrollment accounts.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_billing_account(
        self,
        billing_account_id: str,
        benefit_utilization_summaries_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account.
        This API supports only enrollment accounts.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_billing_account(
        self,
        billing_account_id: str,
        benefit_utilization_summaries_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account.
        This API supports only enrollment accounts.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_generate_by_billing_account(
        self,
        billing_account_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account.
        This API supports only enrollment accounts.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Is one of the following types: BenefitUtilizationSummariesRequest, JSON, IO[bytes]
         Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._generate_by_billing_account_initial(
                billing_account_id=billing_account_id,
                benefit_utilization_summaries_request=benefit_utilization_summaries_request,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BenefitUtilizationSummariesOperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _generate_by_billing_profile_initial(
        self,
        billing_account_id: str,
        billing_profile_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)):
            _content = benefit_utilization_summaries_request
        else:
            _content = json.dumps(benefit_utilization_summaries_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_benefit_utilization_summaries_report_generate_by_billing_profile_request(
            billing_account_id=billing_account_id,
            billing_profile_id=billing_profile_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ArmErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_generate_by_billing_profile(
        self,
        billing_account_id: str,
        billing_profile_id: str,
        benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account
        and billing profile.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param billing_profile_id: Billing Profile ID. Required.
        :type billing_profile_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_billing_profile(
        self,
        billing_account_id: str,
        billing_profile_id: str,
        benefit_utilization_summaries_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account
        and billing profile.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param billing_profile_id: Billing Profile ID. Required.
        :type billing_profile_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_billing_profile(
        self,
        billing_account_id: str,
        billing_profile_id: str,
        benefit_utilization_summaries_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account
        and billing profile.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param billing_profile_id: Billing Profile ID. Required.
        :type billing_profile_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_generate_by_billing_profile(
        self,
        billing_account_id: str,
        billing_profile_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided billing account
        and billing profile.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param billing_profile_id: Billing Profile ID. Required.
        :type billing_profile_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Is one of the following types: BenefitUtilizationSummariesRequest, JSON, IO[bytes]
         Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._generate_by_billing_profile_initial(
                billing_account_id=billing_account_id,
                billing_profile_id=billing_profile_id,
                benefit_utilization_summaries_request=benefit_utilization_summaries_request,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BenefitUtilizationSummariesOperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _generate_by_reservation_order_id_initial(  # pylint: disable=name-too-long
        self,
        reservation_order_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)):
            _content = benefit_utilization_summaries_request
        else:
            _content = json.dumps(benefit_utilization_summaries_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_benefit_utilization_summaries_report_generate_by_reservation_order_id_request(
            reservation_order_id=reservation_order_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ArmErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_generate_by_reservation_order_id(
        self,
        reservation_order_id: str,
        benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation
        order.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_reservation_order_id(
        self,
        reservation_order_id: str,
        benefit_utilization_summaries_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation
        order.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_reservation_order_id(
        self,
        reservation_order_id: str,
        benefit_utilization_summaries_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation
        order.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_generate_by_reservation_order_id(
        self,
        reservation_order_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation
        order.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Is one of the following types: BenefitUtilizationSummariesRequest, JSON, IO[bytes]
         Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._generate_by_reservation_order_id_initial(
                reservation_order_id=reservation_order_id,
                benefit_utilization_summaries_request=benefit_utilization_summaries_request,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BenefitUtilizationSummariesOperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _generate_by_reservation_id_initial(
        self,
        reservation_order_id: str,
        reservation_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)):
            _content = benefit_utilization_summaries_request
        else:
            _content = json.dumps(benefit_utilization_summaries_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_benefit_utilization_summaries_report_generate_by_reservation_id_request(
            reservation_order_id=reservation_order_id,
            reservation_id=reservation_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ArmErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_generate_by_reservation_id(
        self,
        reservation_order_id: str,
        reservation_id: str,
        benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param reservation_id: Reservation ID. Required.
        :type reservation_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_reservation_id(
        self,
        reservation_order_id: str,
        reservation_id: str,
        benefit_utilization_summaries_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param reservation_id: Reservation ID. Required.
        :type reservation_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_reservation_id(
        self,
        reservation_order_id: str,
        reservation_id: str,
        benefit_utilization_summaries_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param reservation_id: Reservation ID. Required.
        :type reservation_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_generate_by_reservation_id(
        self,
        reservation_order_id: str,
        reservation_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided reservation.

        :param reservation_order_id: Reservation Order ID. Required.
        :type reservation_order_id: str
        :param reservation_id: Reservation ID. Required.
        :type reservation_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Is one of the following types: BenefitUtilizationSummariesRequest, JSON, IO[bytes]
         Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._generate_by_reservation_id_initial(
                reservation_order_id=reservation_order_id,
                reservation_id=reservation_id,
                benefit_utilization_summaries_request=benefit_utilization_summaries_request,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BenefitUtilizationSummariesOperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _generate_by_savings_plan_order_id_initial(  # pylint: disable=name-too-long
        self,
        savings_plan_order_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)):
            _content = benefit_utilization_summaries_request
        else:
            _content = json.dumps(benefit_utilization_summaries_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_benefit_utilization_summaries_report_generate_by_savings_plan_order_id_request(
            savings_plan_order_id=savings_plan_order_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ArmErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_generate_by_savings_plan_order_id(
        self,
        savings_plan_order_id: str,
        benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan
        order.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_savings_plan_order_id(
        self,
        savings_plan_order_id: str,
        benefit_utilization_summaries_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan
        order.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_savings_plan_order_id(
        self,
        savings_plan_order_id: str,
        benefit_utilization_summaries_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan
        order.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_generate_by_savings_plan_order_id(
        self,
        savings_plan_order_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan
        order.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Is one of the following types: BenefitUtilizationSummariesRequest, JSON, IO[bytes]
         Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._generate_by_savings_plan_order_id_initial(
                savings_plan_order_id=savings_plan_order_id,
                benefit_utilization_summaries_request=benefit_utilization_summaries_request,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BenefitUtilizationSummariesOperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _generate_by_savings_plan_id_initial(
        self,
        savings_plan_order_id: str,
        savings_plan_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(benefit_utilization_summaries_request, (IOBase, bytes)):
            _content = benefit_utilization_summaries_request
        else:
            _content = json.dumps(benefit_utilization_summaries_request, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_benefit_utilization_summaries_report_generate_by_savings_plan_id_request(
            savings_plan_order_id=savings_plan_order_id,
            savings_plan_id=savings_plan_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ArmErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_generate_by_savings_plan_id(
        self,
        savings_plan_order_id: str,
        savings_plan_id: str,
        benefit_utilization_summaries_request: _models.BenefitUtilizationSummariesRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: Savings plan ID. Required.
        :type savings_plan_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_savings_plan_id(
        self,
        savings_plan_order_id: str,
        savings_plan_id: str,
        benefit_utilization_summaries_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: Savings plan ID. Required.
        :type savings_plan_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_generate_by_savings_plan_id(
        self,
        savings_plan_order_id: str,
        savings_plan_id: str,
        benefit_utilization_summaries_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: Savings plan ID. Required.
        :type savings_plan_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Required.
        :type benefit_utilization_summaries_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_generate_by_savings_plan_id(
        self,
        savings_plan_order_id: str,
        savings_plan_id: str,
        benefit_utilization_summaries_request: Union[_models.BenefitUtilizationSummariesRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus]:
        """Triggers generation of a benefit utilization summaries report for the provided savings plan.

        :param savings_plan_order_id: Savings plan order ID. Required.
        :type savings_plan_order_id: str
        :param savings_plan_id: Savings plan ID. Required.
        :type savings_plan_id: str
        :param benefit_utilization_summaries_request: Async Benefit Utilization Summary report to be
         created. Is one of the following types: BenefitUtilizationSummariesRequest, JSON, IO[bytes]
         Required.
        :type benefit_utilization_summaries_request:
         ~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesRequest or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns BenefitUtilizationSummariesOperationStatus.
         The BenefitUtilizationSummariesOperationStatus is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.BenefitUtilizationSummariesOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.BenefitUtilizationSummariesOperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._generate_by_savings_plan_id_initial(
                savings_plan_order_id=savings_plan_order_id,
                savings_plan_id=savings_plan_id,
                benefit_utilization_summaries_request=benefit_utilization_summaries_request,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.BenefitUtilizationSummariesOperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.BenefitUtilizationSummariesOperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class GenerateDetailedCostReportOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`generate_detailed_cost_report` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _create_operation_initial(
        self,
        scope: str,
        parameters: Union[_models.GenerateDetailedCostReportDefinition, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_generate_detailed_cost_report_create_operation_request(
            scope=scope,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.GenerateDetailedCostReportErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Azure-Consumption-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-Consumption-AsyncOperation")
            )

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def begin_create_operation(
        self,
        scope: str,
        parameters: _models.GenerateDetailedCostReportDefinition,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]:
        """Generates the detailed cost report for provided date range, billing period(only enterprise
        customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header
        Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the
        operation will provide the status and if the operation is completed the blob file where
        generated detailed cost report is being stored.

        :param scope: The ARM Resource ID for subscription, resource group, billing account, or other
         billing scopes. For details, see `https://aka.ms/costmgmt/scopes
         <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create detailed cost report operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns GenerateDetailedCostReportOperationResult.
         The GenerateDetailedCostReportOperationResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_operation(
        self, scope: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]:
        """Generates the detailed cost report for provided date range, billing period(only enterprise
        customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header
        Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the
        operation will provide the status and if the operation is completed the blob file where
        generated detailed cost report is being stored.

        :param scope: The ARM Resource ID for subscription, resource group, billing account, or other
         billing scopes. For details, see `https://aka.ms/costmgmt/scopes
         <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create detailed cost report operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns GenerateDetailedCostReportOperationResult.
         The GenerateDetailedCostReportOperationResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_operation(
        self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]:
        """Generates the detailed cost report for provided date range, billing period(only enterprise
        customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header
        Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the
        operation will provide the status and if the operation is completed the blob file where
        generated detailed cost report is being stored.

        :param scope: The ARM Resource ID for subscription, resource group, billing account, or other
         billing scopes. For details, see `https://aka.ms/costmgmt/scopes
         <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create detailed cost report operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns GenerateDetailedCostReportOperationResult.
         The GenerateDetailedCostReportOperationResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_operation(
        self,
        scope: str,
        parameters: Union[_models.GenerateDetailedCostReportDefinition, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult]:
        """Generates the detailed cost report for provided date range, billing period(only enterprise
        customers) or Invoice ID asynchronously at a certain scope. Call returns a 202 with header
        Azure-Consumption-AsyncOperation providing a link to the operation created. A call on the
        operation will provide the status and if the operation is completed the blob file where
        generated detailed cost report is being stored.

        :param scope: The ARM Resource ID for subscription, resource group, billing account, or other
         billing scopes. For details, see `https://aka.ms/costmgmt/scopes
         <https://aka.ms/costmgmt/scopes>`_. Required.
        :type scope: str
        :param parameters: Parameters supplied to the Create detailed cost report operation. Is one of
         the following types: GenerateDetailedCostReportDefinition, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.GenerateDetailedCostReportDefinition or
         JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns GenerateDetailedCostReportOperationResult.
         The GenerateDetailedCostReportOperationResult is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.GenerateDetailedCostReportOperationResult]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.GenerateDetailedCostReportOperationResult] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._create_operation_initial(
                scope=scope,
                parameters=parameters,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.GenerateDetailedCostReportOperationResult, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.GenerateDetailedCostReportOperationResult](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class ForecastOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`forecast` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @overload
    async def usage(
        self,
        scope: str,
        parameters: _models.ForecastDefinition,
        *,
        filter: Optional[str] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> Optional[_models.ForecastResult]:
        """Lists the forecast charges for scope defined.

        :param scope: The scope associated with forecast operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation.
         Required.
        :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ForecastResult or None. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def usage(
        self,
        scope: str,
        parameters: JSON,
        *,
        filter: Optional[str] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> Optional[_models.ForecastResult]:
        """Lists the forecast charges for scope defined.

        :param scope: The scope associated with forecast operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation.
         Required.
        :type parameters: JSON
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ForecastResult or None. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def usage(
        self,
        scope: str,
        parameters: IO[bytes],
        *,
        filter: Optional[str] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> Optional[_models.ForecastResult]:
        """Lists the forecast charges for scope defined.

        :param scope: The scope associated with forecast operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation.
         Required.
        :type parameters: IO[bytes]
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ForecastResult or None. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def usage(
        self,
        scope: str,
        parameters: Union[_models.ForecastDefinition, JSON, IO[bytes]],
        *,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> Optional[_models.ForecastResult]:
        """Lists the forecast charges for scope defined.

        :param scope: The scope associated with forecast operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Forecast Config operation. Is one
         of the following types: ForecastDefinition, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or JSON or IO[bytes]
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :return: ForecastResult or None. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[Optional[_models.ForecastResult]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_forecast_usage_request(
            scope=scope,
            filter=filter,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = None
        if response.status_code == 200:
            if _stream:
                deserialized = response.iter_bytes() if _decompress else response.iter_raw()
            else:
                deserialized = _deserialize(_models.ForecastResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def external_cloud_provider_usage(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: _models.ForecastDefinition,
        *,
        filter: Optional[str] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ForecastResult:
        """Lists the forecast charges for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ForecastResult. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def external_cloud_provider_usage(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: JSON,
        *,
        filter: Optional[str] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ForecastResult:
        """Lists the forecast charges for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Required.
        :type parameters: JSON
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ForecastResult. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def external_cloud_provider_usage(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: IO[bytes],
        *,
        filter: Optional[str] = None,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ForecastResult:
        """Lists the forecast charges for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Required.
        :type parameters: IO[bytes]
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ForecastResult. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def external_cloud_provider_usage(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: Union[_models.ForecastDefinition, JSON, IO[bytes]],
        *,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.ForecastResult:
        """Lists the forecast charges for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Is one of the following types: ForecastDefinition, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.ForecastDefinition or JSON or IO[bytes]
        :keyword filter: May be used to filter forecasts by properties/usageDate (Utc time),
         properties/chargeType or properties/grain. The filter supports 'eq', 'lt', 'gt', 'le', 'ge',
         and 'and'. It does not currently support 'ne', 'or', or 'not'. Default value is None.
        :paramtype filter: str
        :return: ForecastResult. The ForecastResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.ForecastResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ForecastResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_forecast_external_cloud_provider_usage_request(
            external_cloud_provider_type=external_cloud_provider_type,
            external_cloud_provider_id=external_cloud_provider_id,
            filter=filter,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ForecastResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class DimensionsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`dimensions` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        scope: str,
        *,
        filter: Optional[str] = None,
        expand: Optional[str] = None,
        skiptoken: Optional[str] = None,
        top: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Dimension"]:
        """Lists the dimensions by the defined scope.

        :param scope: The scope associated with dimension operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId}' for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         'providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :keyword filter: May be used to filter dimensions by properties/category,
         properties/usageStart, properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le',
         'ge'. Default value is None.
        :paramtype filter: str
        :keyword expand: May be used to expand the properties/data within a dimension category. By
         default, data is not included when listing dimensions. Default value is None.
        :paramtype expand: str
        :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a skiptoken parameter that specifies a starting point to use for subsequent calls.
         Default value is None.
        :paramtype skiptoken: str
        :keyword top: May be used to limit the number of results to the most recent N dimension data.
         Default value is None.
        :paramtype top: int
        :return: An iterator like instance of Dimension
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Dimension]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_dimensions_list_request(
                    scope=scope,
                    filter=filter,
                    expand=expand,
                    skiptoken=skiptoken,
                    top=top,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Dimension],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200, 204]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def by_external_cloud_provider_type(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        *,
        filter: Optional[str] = None,
        expand: Optional[str] = None,
        skiptoken: Optional[str] = None,
        top: Optional[int] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.Dimension"]:
        """Lists the dimensions by the external cloud provider type.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :keyword filter: May be used to filter dimensions by properties/category,
         properties/usageStart, properties/usageEnd. Supported operators are 'eq','lt', 'gt', 'le',
         'ge'. Default value is None.
        :paramtype filter: str
        :keyword expand: May be used to expand the properties/data within a dimension category. By
         default, data is not included when listing dimensions. Default value is None.
        :paramtype expand: str
        :keyword skiptoken: Skiptoken is only used if a previous operation returned a partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a skiptoken parameter that specifies a starting point to use for subsequent calls.
         Default value is None.
        :paramtype skiptoken: str
        :keyword top: May be used to limit the number of results to the most recent N dimension data.
         Default value is None.
        :paramtype top: int
        :return: An iterator like instance of Dimension
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.costmanagement.models.Dimension]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Dimension]] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_dimensions_by_external_cloud_provider_type_request(
                    external_cloud_provider_type=external_cloud_provider_type,
                    external_cloud_provider_id=external_cloud_provider_id,
                    filter=filter,
                    expand=expand,
                    skiptoken=skiptoken,
                    top=top,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET",
                    urllib.parse.urljoin(next_link, _parsed_next_link.path),
                    headers=_headers,
                    params=_next_request_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Dimension],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class QueryOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`query` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @overload
    async def usage(
        self, scope: str, parameters: _models.QueryDefinition, *, content_type: str = "application/json", **kwargs: Any
    ) -> Optional[_models.QueryResult]:
        """Query the usage data for scope defined.

        :param scope: The scope associated with query and export operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QueryResult or None. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def usage(
        self, scope: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> Optional[_models.QueryResult]:
        """Query the usage data for scope defined.

        :param scope: The scope associated with query and export operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QueryResult or None. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def usage(
        self, scope: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> Optional[_models.QueryResult]:
        """Query the usage data for scope defined.

        :param scope: The scope associated with query and export operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QueryResult or None. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def usage(
        self, scope: str, parameters: Union[_models.QueryDefinition, JSON, IO[bytes]], **kwargs: Any
    ) -> Optional[_models.QueryResult]:
        """Query the usage data for scope defined.

        :param scope: The scope associated with query and export operations. This includes
         '/subscriptions/{subscriptionId}/' for subscription scope,
         '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}' for Billing Account scope and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/departments/{departmentId}'
         for Department scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/enrollmentAccounts/{enrollmentAccountId}'
         for EnrollmentAccount scope,
         '/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group
         scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}'
         for billingProfile scope,
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/invoiceSections/{invoiceSectionId}'
         for invoiceSection scope, and
         '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/customers/{customerId}'
         specific for partners. Required.
        :type scope: str
        :param parameters: Parameters supplied to the CreateOrUpdate Query Config operation. Is one of
         the following types: QueryDefinition, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or JSON or IO[bytes]
        :return: QueryResult or None. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult or None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[Optional[_models.QueryResult]] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_query_usage_request(
            scope=scope,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = None
        if response.status_code == 200:
            if _stream:
                deserialized = response.iter_bytes() if _decompress else response.iter_raw()
            else:
                deserialized = _deserialize(_models.QueryResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @overload
    async def usage_by_external_cloud_provider_type(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: _models.QueryDefinition,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QueryResult:
        """Query the usage data for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Required.
        :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QueryResult. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def usage_by_external_cloud_provider_type(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QueryResult:
        """Query the usage data for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Required.
        :type parameters: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QueryResult. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def usage_by_external_cloud_provider_type(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.QueryResult:
        """Query the usage data for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Required.
        :type parameters: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: QueryResult. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def usage_by_external_cloud_provider_type(
        self,
        external_cloud_provider_type: Union[str, _models.ExternalCloudProviderType],
        external_cloud_provider_id: str,
        parameters: Union[_models.QueryDefinition, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.QueryResult:
        """Query the usage data for external cloud provider type defined.

        :param external_cloud_provider_type: The external cloud provider type associated with
         dimension/query operations. This includes 'externalSubscriptions' for linked account and
         'externalBillingAccounts' for consolidated account. Known values are: "externalSubscriptions"
         and "externalBillingAccounts". Required.
        :type external_cloud_provider_type: str or
         ~azure.mgmt.costmanagement.models.ExternalCloudProviderType
        :param external_cloud_provider_id: This can be '{externalSubscriptionId}' for linked account or
         '{externalBillingAccountId}' for consolidated account used with dimension/query operations.
         Required.
        :type external_cloud_provider_id: str
        :param parameters: The request body. Is one of the following types: QueryDefinition, JSON,
         IO[bytes] Required.
        :type parameters: ~azure.mgmt.costmanagement.models.QueryDefinition or JSON or IO[bytes]
        :return: QueryResult. The QueryResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.costmanagement.models.QueryResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.QueryResult] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _content = None
        if isinstance(parameters, (IOBase, bytes)):
            _content = parameters
        else:
            _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

        _request = build_query_usage_by_external_cloud_provider_type_request(
            external_cloud_provider_type=external_cloud_provider_type,
            external_cloud_provider_id=external_cloud_provider_id,
            content_type=content_type,
            api_version=self._config.api_version,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.QueryResult, response.json())

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore


class GenerateReservationDetailsReportOperations:  # pylint: disable=name-too-long
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`generate_reservation_details_report` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _by_billing_account_id_initial(
        self, billing_account_id: str, *, start_date: str, end_date: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_generate_reservation_details_report_by_billing_account_id_request(
            billing_account_id=billing_account_id,
            start_date=start_date,
            end_date=end_date,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_by_billing_account_id(
        self, billing_account_id: str, *, start_date: str, end_date: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationStatus]:
        """Generates the reservations details report for provided date range asynchronously based on
        enrollment id. The Reservation usage details can be viewed only by certain enterprise roles.
        For more details on the roles see,
        `https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role
        <https://docs.microsoft.com/en-us/azure/cost-management-billing/manage/understand-ea-roles#usage-and-costs-access-by-role>`_.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :keyword start_date: Start Date. Required.
        :paramtype start_date: str
        :keyword end_date: End Date. Required.
        :paramtype end_date: str
        :return: An instance of AsyncLROPoller that returns OperationStatus. The OperationStatus is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._by_billing_account_id_initial(
                billing_account_id=billing_account_id,
                start_date=start_date,
                end_date=end_date,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.OperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.OperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.OperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _by_billing_profile_id_initial(
        self, billing_account_id: str, billing_profile_id: str, *, start_date: str, end_date: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_generate_reservation_details_report_by_billing_profile_id_request(
            billing_account_id=billing_account_id,
            billing_profile_id=billing_profile_id,
            start_date=start_date,
            end_date=end_date,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_by_billing_profile_id(
        self, billing_account_id: str, billing_profile_id: str, *, start_date: str, end_date: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationStatus]:
        """Generates the reservations details report for provided date range asynchronously by billing
        profile. The Reservation usage details can be viewed by only certain enterprise roles by
        default. For more details on the roles see,
        `https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access
        <https://docs.microsoft.com/en-us/azure/cost-management-billing/reservations/reservation-utilization#view-utilization-in-the-azure-portal-with-azure-rbac-access>`_.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param billing_profile_id: Billing Profile ID. Required.
        :type billing_profile_id: str
        :keyword start_date: Start Date. Required.
        :paramtype start_date: str
        :keyword end_date: End Date. Required.
        :paramtype end_date: str
        :return: An instance of AsyncLROPoller that returns OperationStatus. The OperationStatus is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._by_billing_profile_id_initial(
                billing_account_id=billing_account_id,
                billing_profile_id=billing_profile_id,
                start_date=start_date,
                end_date=end_date,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.OperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.OperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.OperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )


class PriceSheetOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.costmanagement.aio.CostManagementClient`'s
        :attr:`price_sheet` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: CostManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    async def _download_by_invoice_initial(
        self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_price_sheet_download_by_invoice_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            invoice_name=invoice_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_download_by_invoice(
        self, billing_account_name: str, billing_profile_name: str, invoice_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.DownloadURL]:
        """Gets a URL to download the pricesheet for an invoice. The operation is supported for billing
        accounts with agreement type Microsoft Partner Agreement or Microsoft Customer Agreement.

        :param billing_account_name: BillingAccount ID. Required.
        :type billing_account_name: str
        :param billing_profile_name: Billing Profile Name. Required.
        :type billing_profile_name: str
        :param invoice_name: The ID that uniquely identifies an invoice. Required.
        :type invoice_name: str
        :return: An instance of AsyncLROPoller that returns DownloadURL. The DownloadURL is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.DownloadURL]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.DownloadURL] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_by_invoice_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                invoice_name=invoice_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.DownloadURL, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.DownloadURL].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.DownloadURL](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _download_by_billing_profile_initial(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_price_sheet_download_by_billing_profile_request(
            billing_account_name=billing_account_name,
            billing_profile_name=billing_profile_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["OData-EntityId"] = self._deserialize("str", response.headers.get("OData-EntityId"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_download_by_billing_profile(
        self, billing_account_name: str, billing_profile_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.PricesheetDownloadProperties]:
        """Gets a URL to download the current month's pricesheet for a billing profile. The operation is
        supported for billing accounts with agreement type Microsoft Partner Agreement or Microsoft
        Customer Agreement.

        You can use the new 2023-09-01 API version for billing periods January 2023 onwards. Azure
        Reserved Instance (RI) pricing is only available through the new version of the API.

        Due to Azure product growth, the Azure price sheet download experience in this preview version
        will be updated from a single csv/json file to a Zip file containing multiple csv/json files,
        each with max size of 75MB.

        :param billing_account_name: BillingAccount ID. Required.
        :type billing_account_name: str
        :param billing_profile_name: Billing Profile Name. Required.
        :type billing_profile_name: str
        :return: An instance of AsyncLROPoller that returns PricesheetDownloadProperties. The
         PricesheetDownloadProperties is compatible with MutableMapping
        :rtype:
         ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.PricesheetDownloadProperties]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.PricesheetDownloadProperties] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_by_billing_profile_initial(
                billing_account_name=billing_account_name,
                billing_profile_name=billing_profile_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.PricesheetDownloadProperties, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.PricesheetDownloadProperties].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.PricesheetDownloadProperties](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    async def _download_by_billing_account_initial(
        self, billing_account_id: str, billing_period_name: str, **kwargs: Any
    ) -> AsyncIterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_price_sheet_download_by_billing_account_request(
            billing_account_id=billing_account_id,
            billing_period_name=billing_period_name,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ArmErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_download_by_billing_account(
        self, billing_account_id: str, billing_period_name: str, **kwargs: Any
    ) -> AsyncLROPoller[_models.OperationStatus]:
        """Generates the pricesheet for the provided billing period asynchronously based on the Enrollment
        ID. This is for Enterprise Agreement customers.

        **Migrate to version 2025-03-01**

        You can use the 2025-03-01 API version with the new URI:

        '/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingPeriods/{billingPeriodName}/providers/Microsoft.CostManagement/pricesheets/default/download'

        With a new schema detailed below, the new version of the price sheet provides additional
        information and includes prices for Azure Reserved Instances (RI) for the current billing
        period. We recommend downloading an Azure Price Sheet for when entering a new billing period if
        you would maintain an ongoing record of past Azure Reserved Instance (RI) pricing.

        The EA Azure price sheet is available for billing periods in the past 13 months. To request a
        price sheet for a billing period older than 13 months, please contact support.

        The Azure price sheet download experience has been updated from a single .csv file to a zip
        file containing multiple .csv files, each with max size of 75MB. The 2023-11-01 version has
        been upgraded to use http POST method; details can be found below.

        All versions of the Microsoft.Consumption Azure Price Sheet - Download by Billing Account
        (including 2022-06-01, 2021-10-01, 2020-01-01-preview, 2019-10-01, 2019-05-01) are scheduled to
        be retired on 01 June 2026 and will no longer be supported after this date.

        :param billing_account_id: BillingAccount ID. Required.
        :type billing_account_id: str
        :param billing_period_name: Billing Period Name. Required.
        :type billing_period_name: str
        :return: An instance of AsyncLROPoller that returns OperationStatus. The OperationStatus is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.costmanagement.models.OperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._download_by_billing_account_initial(
                billing_account_id=billing_account_id,
                billing_period_name=billing_period_name,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.OperationStatus, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }

        if polling is True:
            polling_method: AsyncPollingMethod = cast(
                AsyncPollingMethod, AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller[_models.OperationStatus].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.OperationStatus](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )
