# 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
import datetime
from io import IOBase
import json
from typing import Any, AsyncIterator, Callable, IO, Literal, Optional, TypeVar, Union, cast, overload

from azure.core import AsyncPipelineClient
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    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_attestations_create_or_update_at_resource_group_request,
    build_attestations_create_or_update_at_resource_request,
    build_attestations_create_or_update_at_subscription_request,
    build_attestations_delete_at_resource_group_request,
    build_attestations_delete_at_resource_request,
    build_attestations_delete_at_subscription_request,
    build_attestations_get_at_resource_group_request,
    build_attestations_get_at_resource_request,
    build_attestations_get_at_subscription_request,
    build_attestations_list_for_resource_group_request,
    build_attestations_list_for_resource_request,
    build_attestations_list_for_subscription_request,
    build_component_policy_states_list_query_results_for_policy_definition_request,
    build_component_policy_states_list_query_results_for_resource_group_level_policy_assignment_request,
    build_component_policy_states_list_query_results_for_resource_group_request,
    build_component_policy_states_list_query_results_for_resource_request,
    build_component_policy_states_list_query_results_for_subscription_level_policy_assignment_request,
    build_component_policy_states_list_query_results_for_subscription_request,
    build_operations_list_request,
    build_policy_events_list_query_results_for_management_group_request,
    build_policy_events_list_query_results_for_policy_definition_request,
    build_policy_events_list_query_results_for_policy_set_definition_request,
    build_policy_events_list_query_results_for_resource_group_level_policy_assignment_request,
    build_policy_events_list_query_results_for_resource_group_request,
    build_policy_events_list_query_results_for_resource_request,
    build_policy_events_list_query_results_for_subscription_level_policy_assignment_request,
    build_policy_events_list_query_results_for_subscription_request,
    build_policy_metadata_get_resource_request,
    build_policy_metadata_list_request,
    build_policy_restrictions_check_at_management_group_scope_request,
    build_policy_restrictions_check_at_resource_group_scope_request,
    build_policy_restrictions_check_at_subscription_scope_request,
    build_policy_states_list_query_results_for_management_group_request,
    build_policy_states_list_query_results_for_policy_definition_request,
    build_policy_states_list_query_results_for_policy_set_definition_request,
    build_policy_states_list_query_results_for_resource_group_level_policy_assignment_request,
    build_policy_states_list_query_results_for_resource_group_request,
    build_policy_states_list_query_results_for_resource_request,
    build_policy_states_list_query_results_for_subscription_level_policy_assignment_request,
    build_policy_states_list_query_results_for_subscription_request,
    build_policy_states_summarize_for_management_group_request,
    build_policy_states_summarize_for_policy_definition_request,
    build_policy_states_summarize_for_policy_set_definition_request,
    build_policy_states_summarize_for_resource_group_level_policy_assignment_request,
    build_policy_states_summarize_for_resource_group_request,
    build_policy_states_summarize_for_resource_request,
    build_policy_states_summarize_for_subscription_level_policy_assignment_request,
    build_policy_states_summarize_for_subscription_request,
    build_policy_states_trigger_resource_group_evaluation_request,
    build_policy_states_trigger_subscription_evaluation_request,
    build_policy_tracked_resources_list_query_results_for_management_group_request,
    build_policy_tracked_resources_list_query_results_for_resource_group_request,
    build_policy_tracked_resources_list_query_results_for_resource_request,
    build_policy_tracked_resources_list_query_results_for_subscription_request,
    build_remediations_cancel_at_management_group_request,
    build_remediations_cancel_at_resource_group_request,
    build_remediations_cancel_at_resource_request,
    build_remediations_cancel_at_subscription_request,
    build_remediations_create_or_update_at_management_group_request,
    build_remediations_create_or_update_at_resource_group_request,
    build_remediations_create_or_update_at_resource_request,
    build_remediations_create_or_update_at_subscription_request,
    build_remediations_delete_at_management_group_request,
    build_remediations_delete_at_resource_group_request,
    build_remediations_delete_at_resource_request,
    build_remediations_delete_at_subscription_request,
    build_remediations_get_at_management_group_request,
    build_remediations_get_at_resource_group_request,
    build_remediations_get_at_resource_request,
    build_remediations_get_at_subscription_request,
    build_remediations_list_deployments_at_management_group_request,
    build_remediations_list_deployments_at_resource_group_request,
    build_remediations_list_deployments_at_resource_request,
    build_remediations_list_deployments_at_subscription_request,
    build_remediations_list_for_management_group_request,
    build_remediations_list_for_resource_group_request,
    build_remediations_list_for_resource_request,
    build_remediations_list_for_subscription_request,
)
from .._configuration import PolicyInsightsClientConfiguration

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


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'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: PolicyInsightsClientConfiguration = 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 list(self, **kwargs: Any) -> _models.OperationsListResults:
        """Lists available operations.

        :return: OperationsListResults. The OperationsListResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.OperationsListResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.OperationsListResults] = kwargs.pop("cls", None)

        _request = build_operations_list_request(
            api_version=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.QueryFailure,
                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.OperationsListResults, response.json())

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

        return deserialized  # type: ignore


class RemediationsOperations:  # pylint: disable=too-many-public-methods
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`remediations` 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: PolicyInsightsClientConfiguration = 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_at_management_group(
        self, management_group_id: str, remediation_name: str, **kwargs: Any
    ) -> _models.Remediation:
        """Gets an existing remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_get_at_management_group_request(
            management_group_id=management_group_id,
            remediation_name=remediation_name,
            management_groups_namespace=management_groups_namespace,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def create_or_update_at_management_group(
        self,
        management_group_id: str,
        remediation_name: str,
        parameters: _models.Remediation,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_management_group(
        self,
        management_group_id: str,
        remediation_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_management_group(
        self,
        management_group_id: str,
        remediation_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update_at_management_group(
        self,
        management_group_id: str,
        remediation_name: str,
        parameters: Union[_models.Remediation, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Is one of the following types: Remediation,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation or JSON or IO[bytes]
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Remediation] = 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_remediations_create_or_update_at_management_group_request(
            management_group_id=management_group_id,
            remediation_name=remediation_name,
            management_groups_namespace=management_groups_namespace,
            api_version=api_version,
            content_type=content_type,
            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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_at_management_group(
        self, management_group_id: str, remediation_name: str, **kwargs: Any
    ) -> Optional[_models.Remediation]:
        """Deletes an existing remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation or None. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation 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 = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[Optional[_models.Remediation]] = kwargs.pop("cls", None)

        _request = build_remediations_delete_at_management_group_request(
            management_group_id=management_group_id,
            remediation_name=remediation_name,
            management_groups_namespace=management_groups_namespace,
            api_version=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, 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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_for_management_group(
        self, management_group_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Remediation"]:
        """Gets all remediations for the management group.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Remediation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.Remediation]] = 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_remediations_list_for_management_group_request(
                    management_group_id=management_group_id,
                    top=top,
                    filter=filter,
                    management_groups_namespace=management_groups_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.Remediation],
                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_at_subscription(self, remediation_name: str, **kwargs: Any) -> _models.Remediation:
        """Gets an existing remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_get_at_subscription_request(
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def create_or_update_at_subscription(
        self,
        remediation_name: str,
        parameters: _models.Remediation,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_subscription(
        self, remediation_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_subscription(
        self, remediation_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update_at_subscription(
        self, remediation_name: str, parameters: Union[_models.Remediation, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Is one of the following types: Remediation,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation or JSON or IO[bytes]
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Remediation] = 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_remediations_create_or_update_at_subscription_request(
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_at_subscription(self, remediation_name: str, **kwargs: Any) -> Optional[_models.Remediation]:
        """Deletes an existing remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation or None. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation 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 = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[Optional[_models.Remediation]] = kwargs.pop("cls", None)

        _request = build_remediations_delete_at_subscription_request(
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=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, 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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_for_subscription(
        self, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Remediation"]:
        """Gets all remediations for the subscription.

        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Remediation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.Remediation]] = 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_remediations_list_for_subscription_request(
                    subscription_id=self._config.subscription_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.Remediation],
                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_deployments_at_subscription(
        self, remediation_name: str, *, top: Optional[int] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.RemediationDeployment"]:
        """Gets all deployments for a remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of RemediationDeployment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.RemediationDeployment]] = 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_remediations_list_deployments_at_subscription_request(
                    remediation_name=remediation_name,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.RemediationDeployment],
                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 cancel_at_subscription(self, remediation_name: str, **kwargs: Any) -> _models.Remediation:
        """Cancels a remediation at subscription scope.

        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_cancel_at_subscription_request(
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_at_resource_group(
        self, resource_group_name: str, remediation_name: str, **kwargs: Any
    ) -> _models.Remediation:
        """Gets an existing remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_get_at_resource_group_request(
            resource_group_name=resource_group_name,
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        remediation_name: str,
        parameters: _models.Remediation,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        remediation_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        remediation_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        remediation_name: str,
        parameters: Union[_models.Remediation, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Is one of the following types: Remediation,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation or JSON or IO[bytes]
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Remediation] = 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_remediations_create_or_update_at_resource_group_request(
            resource_group_name=resource_group_name,
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_at_resource_group(
        self, resource_group_name: str, remediation_name: str, **kwargs: Any
    ) -> Optional[_models.Remediation]:
        """Deletes an existing remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation or None. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation 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 = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[Optional[_models.Remediation]] = kwargs.pop("cls", None)

        _request = build_remediations_delete_at_resource_group_request(
            resource_group_name=resource_group_name,
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=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, 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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_for_resource_group(
        self, resource_group_name: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Remediation"]:
        """Gets all remediations for the subscription.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Remediation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.Remediation]] = 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_remediations_list_for_resource_group_request(
                    resource_group_name=resource_group_name,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.Remediation],
                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_deployments_at_resource_group(
        self, resource_group_name: str, remediation_name: str, *, top: Optional[int] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.RemediationDeployment"]:
        """Gets all deployments for a remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of RemediationDeployment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.RemediationDeployment]] = 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_remediations_list_deployments_at_resource_group_request(
                    resource_group_name=resource_group_name,
                    remediation_name=remediation_name,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.RemediationDeployment],
                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 cancel_at_resource_group(
        self, resource_group_name: str, remediation_name: str, **kwargs: Any
    ) -> _models.Remediation:
        """Cancels a remediation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_cancel_at_resource_group_request(
            resource_group_name=resource_group_name,
            remediation_name=remediation_name,
            subscription_id=self._config.subscription_id,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get_at_resource(self, resource_id: str, remediation_name: str, **kwargs: Any) -> _models.Remediation:
        """Gets an existing remediation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_get_at_resource_request(
            resource_id=resource_id,
            remediation_name=remediation_name,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def create_or_update_at_resource(
        self,
        resource_id: str,
        remediation_name: str,
        parameters: _models.Remediation,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_resource(
        self,
        resource_id: str,
        remediation_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update_at_resource(
        self,
        resource_id: str,
        remediation_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. 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: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update_at_resource(
        self,
        resource_id: str,
        remediation_name: str,
        parameters: Union[_models.Remediation, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.Remediation:
        """Creates or updates a remediation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :param parameters: The remediation parameters. Is one of the following types: Remediation,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Remediation or JSON or IO[bytes]
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Remediation] = 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_remediations_create_or_update_at_resource_request(
            resource_id=resource_id,
            remediation_name=remediation_name,
            api_version=api_version,
            content_type=content_type,
            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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_at_resource(
        self, resource_id: str, remediation_name: str, **kwargs: Any
    ) -> Optional[_models.Remediation]:
        """Deletes an existing remediation at individual resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation or None. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation 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 = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[Optional[_models.Remediation]] = kwargs.pop("cls", None)

        _request = build_remediations_delete_at_resource_request(
            resource_id=resource_id,
            remediation_name=remediation_name,
            api_version=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, 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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_for_resource(
        self, resource_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Remediation"]:
        """Gets all remediations for a resource.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Remediation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.Remediation]] = 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_remediations_list_for_resource_request(
                    resource_id=resource_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.Remediation],
                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_deployments_at_resource(
        self, resource_id: str, remediation_name: str, *, top: Optional[int] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.RemediationDeployment"]:
        """Gets all deployments for a remediation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of RemediationDeployment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.RemediationDeployment]] = 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_remediations_list_deployments_at_resource_request(
                    resource_id=resource_id,
                    remediation_name=remediation_name,
                    top=top,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.RemediationDeployment],
                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 cancel_at_resource(self, resource_id: str, remediation_name: str, **kwargs: Any) -> _models.Remediation:
        """Cancel a remediation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_cancel_at_resource_request(
            resource_id=resource_id,
            remediation_name=remediation_name,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_deployments_at_management_group(
        self, management_group_id: str, remediation_name: str, *, top: Optional[int] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.RemediationDeployment"]:
        """Gets all deployments for a remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of RemediationDeployment
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.RemediationDeployment]] = 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_remediations_list_deployments_at_management_group_request(
                    management_group_id=management_group_id,
                    remediation_name=remediation_name,
                    top=top,
                    management_groups_namespace=management_groups_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.RemediationDeployment],
                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 cancel_at_management_group(
        self, management_group_id: str, remediation_name: str, **kwargs: Any
    ) -> _models.Remediation:
        """Cancels a remediation at management group scope.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param remediation_name: The name of the remediation. Required.
        :type remediation_name: str
        :return: Remediation. The Remediation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Remediation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Remediation] = kwargs.pop("cls", None)

        _request = build_remediations_cancel_at_management_group_request(
            management_group_id=management_group_id,
            remediation_name=remediation_name,
            management_groups_namespace=management_groups_namespace,
            api_version=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.Remediation, response.json())

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

        return deserialized  # type: ignore


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`attestations` 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: PolicyInsightsClientConfiguration = 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_at_subscription(self, attestation_name: str, **kwargs: Any) -> _models.Attestation:
        """Gets an existing attestation at subscription scope.

        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :return: Attestation. The Attestation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Attestation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Attestation] = kwargs.pop("cls", None)

        _request = build_attestations_get_at_subscription_request(
            attestation_name=attestation_name,
            subscription_id=self._config.subscription_id,
            api_version=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.Attestation, response.json())

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

        return deserialized  # type: ignore

    async def _create_or_update_at_subscription_initial(  # pylint: disable=name-too-long
        self, attestation_name: str, parameters: Union[_models.Attestation, 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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        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_attestations_create_or_update_at_subscription_request(
            attestation_name=attestation_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            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, 201]:
            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 == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            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

    @overload
    async def begin_create_or_update_at_subscription(
        self,
        attestation_name: str,
        parameters: _models.Attestation,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at subscription scope.

        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Attestation
        :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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_at_subscription(
        self, attestation_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at subscription scope.

        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. 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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_at_subscription(
        self, attestation_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at subscription scope.

        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. 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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_at_subscription(
        self, attestation_name: str, parameters: Union[_models.Attestation, JSON, IO[bytes]], **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at subscription scope.

        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. Is one of the following types: Attestation,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Attestation or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Attestation] = 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_or_update_at_subscription_initial(
                attestation_name=attestation_name,
                parameters=parameters,
                api_version=api_version,
                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.Attestation, 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.Attestation].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.Attestation](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete_at_subscription(self, attestation_name: str, **kwargs: Any) -> None:
        """Deletes an existing attestation at subscription scope.

        :param attestation_name: The name of the attestation. Required.
        :type attestation_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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_attestations_delete_at_subscription_request(
            attestation_name=attestation_name,
            subscription_id=self._config.subscription_id,
            api_version=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_for_subscription(
        self, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Attestation"]:
        """Gets all attestations for the subscription.

        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Attestation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.Attestation]] = 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_attestations_list_for_subscription_request(
                    subscription_id=self._config.subscription_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.Attestation],
                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_at_resource_group(
        self, resource_group_name: str, attestation_name: str, **kwargs: Any
    ) -> _models.Attestation:
        """Gets an existing attestation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :return: Attestation. The Attestation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Attestation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Attestation] = kwargs.pop("cls", None)

        _request = build_attestations_get_at_resource_group_request(
            resource_group_name=resource_group_name,
            attestation_name=attestation_name,
            subscription_id=self._config.subscription_id,
            api_version=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.Attestation, response.json())

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

        return deserialized  # type: ignore

    async def _create_or_update_at_resource_group_initial(  # pylint: disable=name-too-long
        self,
        resource_group_name: str,
        attestation_name: str,
        parameters: Union[_models.Attestation, 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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        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_attestations_create_or_update_at_resource_group_request(
            resource_group_name=resource_group_name,
            attestation_name=attestation_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            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, 201]:
            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 == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            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

    @overload
    async def begin_create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        attestation_name: str,
        parameters: _models.Attestation,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Attestation
        :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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        attestation_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. 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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        attestation_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. 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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_at_resource_group(
        self,
        resource_group_name: str,
        attestation_name: str,
        parameters: Union[_models.Attestation, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. Is one of the following types: Attestation,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Attestation or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Attestation] = 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_or_update_at_resource_group_initial(
                resource_group_name=resource_group_name,
                attestation_name=attestation_name,
                parameters=parameters,
                api_version=api_version,
                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.Attestation, 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.Attestation].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.Attestation](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete_at_resource_group(self, resource_group_name: str, attestation_name: str, **kwargs: Any) -> None:
        """Deletes an existing attestation at resource group scope.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_attestations_delete_at_resource_group_request(
            resource_group_name=resource_group_name,
            attestation_name=attestation_name,
            subscription_id=self._config.subscription_id,
            api_version=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_for_resource_group(
        self, resource_group_name: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Attestation"]:
        """Gets all attestations for the resource group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Attestation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.Attestation]] = 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_attestations_list_for_resource_group_request(
                    resource_group_name=resource_group_name,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.Attestation],
                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_at_resource(self, resource_id: str, attestation_name: str, **kwargs: Any) -> _models.Attestation:
        """Gets an existing attestation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :return: Attestation. The Attestation is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.Attestation
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.Attestation] = kwargs.pop("cls", None)

        _request = build_attestations_get_at_resource_request(
            resource_id=resource_id,
            attestation_name=attestation_name,
            api_version=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.Attestation, response.json())

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

        return deserialized  # type: ignore

    async def _create_or_update_at_resource_initial(
        self,
        resource_id: str,
        attestation_name: str,
        parameters: Union[_models.Attestation, 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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        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_attestations_create_or_update_at_resource_request(
            resource_id=resource_id,
            attestation_name=attestation_name,
            api_version=api_version,
            content_type=content_type,
            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, 201]:
            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 == 201:
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            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

    @overload
    async def begin_create_or_update_at_resource(
        self,
        resource_id: str,
        attestation_name: str,
        parameters: _models.Attestation,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Attestation
        :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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_at_resource(
        self,
        resource_id: str,
        attestation_name: str,
        parameters: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. 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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update_at_resource(
        self,
        resource_id: str,
        attestation_name: str,
        parameters: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. 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 Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update_at_resource(
        self,
        resource_id: str,
        attestation_name: str,
        parameters: Union[_models.Attestation, JSON, IO[bytes]],
        **kwargs: Any
    ) -> AsyncLROPoller[_models.Attestation]:
        """Creates or updates an attestation at resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_name: str
        :param parameters: The attestation parameters. Is one of the following types: Attestation,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.Attestation or JSON or IO[bytes]
        :return: An instance of AsyncLROPoller that returns Attestation. The Attestation is compatible
         with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.Attestation] = 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_or_update_at_resource_initial(
                resource_id=resource_id,
                attestation_name=attestation_name,
                parameters=parameters,
                api_version=api_version,
                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.Attestation, 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.Attestation].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[_models.Attestation](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace_async
    async def delete_at_resource(self, resource_id: str, attestation_name: str, **kwargs: Any) -> None:
        """Deletes an existing attestation at individual resource scope.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param attestation_name: The name of the attestation. Required.
        :type attestation_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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_attestations_delete_at_resource_request(
            resource_id=resource_id,
            attestation_name=attestation_name,
            api_version=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_for_resource(
        self, resource_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.Attestation"]:
        """Gets all attestations for a resource.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of Attestation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Attestation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.Attestation]] = 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_attestations_list_for_resource_request(
                    resource_id=resource_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.Attestation],
                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 PolicyMetadataOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`policy_metadata` 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: PolicyInsightsClientConfiguration = 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_resource(self, resource_name: str, **kwargs: Any) -> _models.PolicyMetadata:
        """Get policy metadata resource.

        :param resource_name: The name of the policy metadata resource. Required.
        :type resource_name: str
        :return: PolicyMetadata. The PolicyMetadata is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.PolicyMetadata
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.PolicyMetadata] = kwargs.pop("cls", None)

        _request = build_policy_metadata_get_resource_request(
            resource_name=resource_name,
            api_version=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.PolicyMetadata, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list(self, *, top: Optional[int] = None, **kwargs: Any) -> AsyncItemPaged["_models.SlimPolicyMetadata"]:
        """Get a list of the policy metadata resources.

        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of SlimPolicyMetadata
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.SlimPolicyMetadata]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.SlimPolicyMetadata]] = 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_policy_metadata_list_request(
                    top=top,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.SlimPolicyMetadata],
                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 PolicyEventsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`policy_events` 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: PolicyInsightsClientConfiguration = 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_query_results_for_management_group(  # pylint: disable=too-many-locals
        self,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        management_group_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the resources under the management group.

        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :param management_group_name: Management group name. Required.
        :type management_group_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_management_group_request(
                    policy_events_resource=policy_events_resource,
                    management_group_name=management_group_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    management_groups_namespace=management_groups_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_subscription(
        self,
        subscription_id: str,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the resources under the subscription.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_subscription_request(
                    subscription_id=subscription_id,
                    policy_events_resource=policy_events_resource,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_resource_group(  # pylint: disable=too-many-locals
        self,
        subscription_id: str,
        resource_group_name: str,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the resources under the resource group.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_resource_group_request(
                    subscription_id=subscription_id,
                    resource_group_name=resource_group_name,
                    policy_events_resource=policy_events_resource,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_resource(  # pylint: disable=too-many-locals
        self,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        resource_id: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        expand: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the resource.

        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword expand: The $expand query parameter. For example, to expand components use
         $expand=components. Default value is None.
        :paramtype expand: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_resource_request(
                    policy_events_resource=policy_events_resource,
                    resource_id=resource_id,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    expand=expand,
                    skip_token=skip_token,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_policy_set_definition(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        policy_set_definition_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the subscription level policy set definition.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :param policy_set_definition_name: Policy set definition name. Required.
        :type policy_set_definition_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_policy_set_definition_request(
                    subscription_id=subscription_id,
                    policy_events_resource=policy_events_resource,
                    policy_set_definition_name=policy_set_definition_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_policy_definition(  # pylint: disable=too-many-locals
        self,
        subscription_id: str,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        policy_definition_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the subscription level policy definition.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :param policy_definition_name: Policy definition name. Required.
        :type policy_definition_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_policy_definition_request(
                    subscription_id=subscription_id,
                    policy_events_resource=policy_events_resource,
                    policy_definition_name=policy_definition_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_subscription_level_policy_assignment(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        policy_assignment_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the subscription level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_subscription_level_policy_assignment_request(
                    subscription_id=subscription_id,
                    policy_events_resource=policy_events_resource,
                    policy_assignment_name=policy_assignment_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_resource_group_level_policy_assignment(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        resource_group_name: str,
        policy_events_resource: Union[str, _models.PolicyEventsResourceType],
        policy_assignment_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyEvent"]:
        """Queries policy events for the resource group level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: Resource group name. Required.
        :type resource_group_name: str
        :param policy_events_resource: The name of the virtual resource under PolicyEvents resource
         type; only "default" is allowed. "default" Required.
        :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyEvent
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyEvent]] = 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_policy_events_list_query_results_for_resource_group_level_policy_assignment_request(
                    subscription_id=subscription_id,
                    resource_group_name=resource_group_name,
                    policy_events_resource=policy_events_resource,
                    policy_assignment_name=policy_assignment_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyEvent],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`policy_states` 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: PolicyInsightsClientConfiguration = 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_query_results_for_management_group(  # pylint: disable=too-many-locals
        self,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        management_group_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the resources under the management group.

        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :param management_group_name: Management group name. Required.
        :type management_group_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_management_group_request(
                    policy_states_resource=policy_states_resource,
                    management_group_name=management_group_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    management_groups_namespace=management_groups_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_management_group(
        self,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        management_group_name: str,
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the resources under the management group.

        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :param management_group_name: Management group name. Required.
        :type management_group_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_management_group_request(
            policy_states_summary_resource=policy_states_summary_resource,
            management_group_name=management_group_name,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            management_groups_namespace=management_groups_namespace,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_query_results_for_subscription(
        self,
        subscription_id: str,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the resources under the subscription.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_subscription_request(
                    subscription_id=subscription_id,
                    policy_states_resource=policy_states_resource,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_subscription(
        self,
        subscription_id: str,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the resources under the subscription.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_subscription_request(
            subscription_id=subscription_id,
            policy_states_summary_resource=policy_states_summary_resource,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_query_results_for_resource_group(  # pylint: disable=too-many-locals
        self,
        subscription_id: str,
        resource_group_name: str,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the resources under the resource group.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_resource_group_request(
                    subscription_id=subscription_id,
                    resource_group_name=resource_group_name,
                    policy_states_resource=policy_states_resource,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_resource_group(
        self,
        subscription_id: str,
        resource_group_name: str,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the resources under the resource group.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_resource_group_request(
            subscription_id=subscription_id,
            resource_group_name=resource_group_name,
            policy_states_summary_resource=policy_states_summary_resource,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_query_results_for_resource(  # pylint: disable=too-many-locals
        self,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        resource_id: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        expand: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the resource.

        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword expand: The $expand query parameter. For example, to expand components use
         $expand=components. Default value is None.
        :paramtype expand: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_resource_request(
                    policy_states_resource=policy_states_resource,
                    resource_id=resource_id,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    expand=expand,
                    skip_token=skip_token,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_resource(
        self,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        resource_id: str,
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the resource.

        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_resource_request(
            policy_states_summary_resource=policy_states_summary_resource,
            resource_id=resource_id,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore

    async def _trigger_subscription_evaluation_initial(
        self, subscription_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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_policy_states_trigger_subscription_evaluation_request(
            subscription_id=subscription_id,
            api_version=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.QueryFailure,
                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["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_trigger_subscription_evaluation(self, subscription_id: str, **kwargs: Any) -> AsyncLROPoller[None]:
        """Triggers a policy evaluation scan for all the resources under the subscription.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[None] = 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._trigger_subscription_evaluation_initial(
                subscription_id=subscription_id,
                api_version=api_version,
                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):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        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[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    async def _trigger_resource_group_evaluation_initial(  # pylint: disable=name-too-long
        self, subscription_id: str, resource_group_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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None)

        _request = build_policy_states_trigger_resource_group_evaluation_request(
            subscription_id=subscription_id,
            resource_group_name=resource_group_name,
            api_version=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.QueryFailure,
                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["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_trigger_resource_group_evaluation(
        self, subscription_id: str, resource_group_name: str, **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Triggers a policy evaluation scan for all the resources under the resource group.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: Resource group name. Required.
        :type resource_group_name: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[None] = 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._trigger_resource_group_evaluation_initial(
                subscription_id=subscription_id,
                resource_group_name=resource_group_name,
                api_version=api_version,
                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):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

        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[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def list_query_results_for_policy_set_definition(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        policy_set_definition_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the subscription level policy set definition.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :param policy_set_definition_name: Policy set definition name. Required.
        :type policy_set_definition_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_policy_set_definition_request(
                    subscription_id=subscription_id,
                    policy_states_resource=policy_states_resource,
                    policy_set_definition_name=policy_set_definition_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_policy_set_definition(
        self,
        subscription_id: str,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        policy_set_definition_name: str,
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the subscription level policy set definition.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :param policy_set_definition_name: Policy set definition name. Required.
        :type policy_set_definition_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_policy_set_definition_request(
            subscription_id=subscription_id,
            policy_states_summary_resource=policy_states_summary_resource,
            policy_set_definition_name=policy_set_definition_name,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            authorization_namespace=authorization_namespace,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_query_results_for_policy_definition(  # pylint: disable=too-many-locals
        self,
        subscription_id: str,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        policy_definition_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the subscription level policy definition.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :param policy_definition_name: Policy definition name. Required.
        :type policy_definition_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_policy_definition_request(
                    subscription_id=subscription_id,
                    policy_states_resource=policy_states_resource,
                    policy_definition_name=policy_definition_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_policy_definition(
        self,
        subscription_id: str,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        policy_definition_name: str,
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the subscription level policy definition.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :param policy_definition_name: Policy definition name. Required.
        :type policy_definition_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_policy_definition_request(
            subscription_id=subscription_id,
            policy_states_summary_resource=policy_states_summary_resource,
            policy_definition_name=policy_definition_name,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            authorization_namespace=authorization_namespace,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_query_results_for_subscription_level_policy_assignment(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        policy_assignment_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the subscription level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_subscription_level_policy_assignment_request(
                    subscription_id=subscription_id,
                    policy_states_resource=policy_states_resource,
                    policy_assignment_name=policy_assignment_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_subscription_level_policy_assignment(  # pylint: disable=name-too-long
        self,
        subscription_id: str,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        policy_assignment_name: str,
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the subscription level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_subscription_level_policy_assignment_request(
            subscription_id=subscription_id,
            policy_states_summary_resource=policy_states_summary_resource,
            policy_assignment_name=policy_assignment_name,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            authorization_namespace=authorization_namespace,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def list_query_results_for_resource_group_level_policy_assignment(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        resource_group_name: str,
        policy_states_resource: Union[str, _models.PolicyStatesResource],
        policy_assignment_name: str,
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        skip_token: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyState"]:
        """Queries policy states for the resource group level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: Resource group name. Required.
        :type resource_group_name: str
        :param policy_states_resource: The virtual resource under PolicyStates resource type. In a
         given time range, 'latest' represents the latest policy state(s), whereas 'default' represents
         all policy state(s). Known values are: "default" and "latest". Required.
        :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword skip_token: Skiptoken is only provided if a previous response returned a partial
         result as a part of nextLink element. Default value is None.
        :paramtype skip_token: str
        :return: An iterator like instance of PolicyState
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[List[_models.PolicyState]] = 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_policy_states_list_query_results_for_resource_group_level_policy_assignment_request(
                    subscription_id=subscription_id,
                    resource_group_name=resource_group_name,
                    policy_states_resource=policy_states_resource,
                    policy_assignment_name=policy_assignment_name,
                    top=top,
                    order_by=order_by,
                    select=select,
                    from_parameter=from_parameter,
                    to=to,
                    filter=filter,
                    apply=apply,
                    skip_token=skip_token,
                    authorization_namespace=authorization_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyState],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@odata.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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def summarize_for_resource_group_level_policy_assignment(  # pylint: disable=name-too-long
        self,
        subscription_id: str,
        resource_group_name: str,
        policy_states_summary_resource: Union[str, _models.PolicyStatesSummaryResourceType],
        policy_assignment_name: str,
        *,
        top: Optional[int] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> _models.SummarizeResults:
        """Summarizes policy states for the resource group level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: Resource group name. Required.
        :type resource_group_name: str
        :param policy_states_summary_resource: The virtual resource under PolicyStates resource type
         for summarize action. In a given time range, 'latest' represents the latest policy state(s) and
         is the only allowed value. "latest" Required.
        :type policy_states_summary_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: SummarizeResults. The SummarizeResults is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.SummarizeResults] = kwargs.pop("cls", None)

        _request = build_policy_states_summarize_for_resource_group_level_policy_assignment_request(
            subscription_id=subscription_id,
            resource_group_name=resource_group_name,
            policy_states_summary_resource=policy_states_summary_resource,
            policy_assignment_name=policy_assignment_name,
            top=top,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            authorization_namespace=authorization_namespace,
            api_version=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.QueryFailure,
                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.SummarizeResults, response.json())

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

        return deserialized  # type: ignore


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`policy_restrictions` 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: PolicyInsightsClientConfiguration = 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 check_at_subscription_scope(
        self, parameters: _models.CheckRestrictionsRequest, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a subscription.

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

    @overload
    async def check_at_subscription_scope(
        self, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a subscription.

        :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: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_at_subscription_scope(
        self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a subscription.

        :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: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_at_subscription_scope(
        self, parameters: Union[_models.CheckRestrictionsRequest, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a subscription.

        :param parameters: The request body. Is one of the following types: CheckRestrictionsRequest,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest or JSON or
         IO[bytes]
        :return: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CheckRestrictionsResult] = 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_policy_restrictions_check_at_subscription_scope_request(
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            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.CheckRestrictionsResult, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def check_at_resource_group_scope(
        self,
        resource_group_name: str,
        parameters: _models.CheckRestrictionsRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a resource group. Use
        this when the resource group the resource will be created in is already known.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param parameters: The request body. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_at_resource_group_scope(
        self, resource_group_name: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a resource group. Use
        this when the resource group the resource will be created in is already known.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: 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: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_at_resource_group_scope(
        self, resource_group_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a resource group. Use
        this when the resource group the resource will be created in is already known.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: 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: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_at_resource_group_scope(
        self,
        resource_group_name: str,
        parameters: Union[_models.CheckRestrictionsRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on a resource within a resource group. Use
        this when the resource group the resource will be created in is already known.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param parameters: The request body. Is one of the following types: CheckRestrictionsRequest,
         JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest or JSON or
         IO[bytes]
        :return: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CheckRestrictionsResult] = 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_policy_restrictions_check_at_resource_group_scope_request(
            resource_group_name=resource_group_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            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.CheckRestrictionsResult, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def check_at_management_group_scope(
        self,
        management_group_id: str,
        parameters: _models.CheckManagementGroupRestrictionsRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on resources within a management group.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param parameters: The check policy restrictions parameters. Required.
        :type parameters: ~azure.mgmt.policyinsights.models.CheckManagementGroupRestrictionsRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_at_management_group_scope(
        self, management_group_id: str, parameters: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on resources within a management group.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param parameters: The check policy restrictions parameters. 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: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_at_management_group_scope(
        self, management_group_id: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on resources within a management group.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param parameters: The check policy restrictions parameters. 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: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_at_management_group_scope(
        self,
        management_group_id: str,
        parameters: Union[_models.CheckManagementGroupRestrictionsRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.CheckRestrictionsResult:
        """Checks what restrictions Azure Policy will place on resources within a management group.

        :param management_group_id: Management group ID. Required.
        :type management_group_id: str
        :param parameters: The check policy restrictions parameters. Is one of the following types:
         CheckManagementGroupRestrictionsRequest, JSON, IO[bytes] Required.
        :type parameters: ~azure.mgmt.policyinsights.models.CheckManagementGroupRestrictionsRequest or
         JSON or IO[bytes]
        :return: CheckRestrictionsResult. The CheckRestrictionsResult is compatible with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.CheckRestrictionsResult] = 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_policy_restrictions_check_at_management_group_scope_request(
            management_group_id=management_group_id,
            management_groups_namespace=management_groups_namespace,
            api_version=api_version,
            content_type=content_type,
            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.CheckRestrictionsResult, response.json())

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

        return deserialized  # type: ignore


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`component_policy_states` 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: PolicyInsightsClientConfiguration = 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 list_query_results_for_subscription(
        self,
        subscription_id: str,
        component_policy_states_resource: Union[str, _models.ComponentPolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        **kwargs: Any
    ) -> _models.ComponentPolicyStatesQueryResults:
        """Queries component policy states under subscription scope.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param component_policy_states_resource: The virtual resource under ComponentPolicyStates
         resource type. In a given time range, 'latest' represents the latest component policy state(s).
         "latest" Required.
        :type component_policy_states_resource: str or
         ~azure.mgmt.policyinsights.models.ComponentPolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :return: ComponentPolicyStatesQueryResults. The ComponentPolicyStatesQueryResults is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.ComponentPolicyStatesQueryResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.ComponentPolicyStatesQueryResults] = kwargs.pop("cls", None)

        _request = build_component_policy_states_list_query_results_for_subscription_request(
            subscription_id=subscription_id,
            component_policy_states_resource=component_policy_states_resource,
            top=top,
            order_by=order_by,
            select=select,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            apply=apply,
            api_version=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.ComponentPolicyStatesQueryResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_query_results_for_resource_group(
        self,
        subscription_id: str,
        resource_group_name: str,
        component_policy_states_resource: Union[str, _models.ComponentPolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        **kwargs: Any
    ) -> _models.ComponentPolicyStatesQueryResults:
        """Queries component policy states under resource group scope.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param component_policy_states_resource: The virtual resource under ComponentPolicyStates
         resource type. In a given time range, 'latest' represents the latest component policy state(s).
         "latest" Required.
        :type component_policy_states_resource: str or
         ~azure.mgmt.policyinsights.models.ComponentPolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :return: ComponentPolicyStatesQueryResults. The ComponentPolicyStatesQueryResults is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.ComponentPolicyStatesQueryResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.ComponentPolicyStatesQueryResults] = kwargs.pop("cls", None)

        _request = build_component_policy_states_list_query_results_for_resource_group_request(
            subscription_id=subscription_id,
            resource_group_name=resource_group_name,
            component_policy_states_resource=component_policy_states_resource,
            top=top,
            order_by=order_by,
            select=select,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            apply=apply,
            api_version=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.ComponentPolicyStatesQueryResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_query_results_for_resource(
        self,
        resource_id: str,
        component_policy_states_resource: Union[str, _models.ComponentPolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        expand: Optional[str] = None,
        **kwargs: Any
    ) -> _models.ComponentPolicyStatesQueryResults:
        """Queries component policy states for the resource.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param component_policy_states_resource: The virtual resource under ComponentPolicyStates
         resource type. In a given time range, 'latest' represents the latest component policy state(s).
         "latest" Required.
        :type component_policy_states_resource: str or
         ~azure.mgmt.policyinsights.models.ComponentPolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :keyword expand: The $expand query parameter. Default value is None.
        :paramtype expand: str
        :return: ComponentPolicyStatesQueryResults. The ComponentPolicyStatesQueryResults is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.ComponentPolicyStatesQueryResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.ComponentPolicyStatesQueryResults] = kwargs.pop("cls", None)

        _request = build_component_policy_states_list_query_results_for_resource_request(
            resource_id=resource_id,
            component_policy_states_resource=component_policy_states_resource,
            top=top,
            order_by=order_by,
            select=select,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            apply=apply,
            expand=expand,
            api_version=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.ComponentPolicyStatesQueryResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_query_results_for_policy_definition(  # pylint: disable=too-many-locals
        self,
        subscription_id: str,
        policy_definition_name: str,
        component_policy_states_resource: Union[str, _models.ComponentPolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        **kwargs: Any
    ) -> _models.ComponentPolicyStatesQueryResults:
        """Queries component policy states for the subscription level policy definition.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_definition_name: Policy definition name. Required.
        :type policy_definition_name: str
        :param component_policy_states_resource: The virtual resource under ComponentPolicyStates
         resource type. In a given time range, 'latest' represents the latest component policy state(s).
         "latest" Required.
        :type component_policy_states_resource: str or
         ~azure.mgmt.policyinsights.models.ComponentPolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :return: ComponentPolicyStatesQueryResults. The ComponentPolicyStatesQueryResults is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.ComponentPolicyStatesQueryResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.ComponentPolicyStatesQueryResults] = kwargs.pop("cls", None)

        _request = build_component_policy_states_list_query_results_for_policy_definition_request(
            subscription_id=subscription_id,
            policy_definition_name=policy_definition_name,
            component_policy_states_resource=component_policy_states_resource,
            top=top,
            order_by=order_by,
            select=select,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            apply=apply,
            authorization_namespace=authorization_namespace,
            api_version=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.ComponentPolicyStatesQueryResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_query_results_for_subscription_level_policy_assignment(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        policy_assignment_name: str,
        component_policy_states_resource: Union[str, _models.ComponentPolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        **kwargs: Any
    ) -> _models.ComponentPolicyStatesQueryResults:
        """Queries component policy states for the subscription level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :param component_policy_states_resource: The virtual resource under ComponentPolicyStates
         resource type. In a given time range, 'latest' represents the latest component policy state(s).
         "latest" Required.
        :type component_policy_states_resource: str or
         ~azure.mgmt.policyinsights.models.ComponentPolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :return: ComponentPolicyStatesQueryResults. The ComponentPolicyStatesQueryResults is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.ComponentPolicyStatesQueryResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.ComponentPolicyStatesQueryResults] = kwargs.pop("cls", None)

        _request = build_component_policy_states_list_query_results_for_subscription_level_policy_assignment_request(
            subscription_id=subscription_id,
            policy_assignment_name=policy_assignment_name,
            component_policy_states_resource=component_policy_states_resource,
            top=top,
            order_by=order_by,
            select=select,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            apply=apply,
            authorization_namespace=authorization_namespace,
            api_version=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.ComponentPolicyStatesQueryResults, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def list_query_results_for_resource_group_level_policy_assignment(  # pylint: disable=name-too-long,too-many-locals
        self,
        subscription_id: str,
        resource_group_name: str,
        policy_assignment_name: str,
        component_policy_states_resource: Union[str, _models.ComponentPolicyStatesResource],
        *,
        top: Optional[int] = None,
        order_by: Optional[str] = None,
        select: Optional[str] = None,
        from_parameter: Optional[datetime.datetime] = None,
        to: Optional[datetime.datetime] = None,
        filter: Optional[str] = None,
        apply: Optional[str] = None,
        **kwargs: Any
    ) -> _models.ComponentPolicyStatesQueryResults:
        """Queries component policy states for the resource group level policy assignment.

        :param subscription_id: The ID of the target subscription. The value must be an UUID. Required.
        :type subscription_id: str
        :param resource_group_name: Resource group name. Required.
        :type resource_group_name: str
        :param policy_assignment_name: Policy assignment name. Required.
        :type policy_assignment_name: str
        :param component_policy_states_resource: The virtual resource under ComponentPolicyStates
         resource type. In a given time range, 'latest' represents the latest component policy state(s).
         "latest" Required.
        :type component_policy_states_resource: str or
         ~azure.mgmt.policyinsights.models.ComponentPolicyStatesResource
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword order_by: Ordering expression using OData notation. One or more comma-separated column
         names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId,
         ResourceId asc". Default value is None.
        :paramtype order_by: str
        :keyword select: Select expression using OData notation. Limits the columns on each record to
         just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". Default value is None.
        :paramtype select: str
        :keyword from_parameter: ISO 8601 formatted timestamp specifying the start time of the interval
         to query. When not specified, the service uses ($to - 1-day). Default value is None.
        :paramtype from_parameter: ~datetime.datetime
        :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query.
         When not specified, the service uses request time. Default value is None.
        :paramtype to: ~datetime.datetime
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :keyword apply: OData apply expression for aggregations. Default value is None.
        :paramtype apply: str
        :return: ComponentPolicyStatesQueryResults. The ComponentPolicyStatesQueryResults is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.policyinsights.models.ComponentPolicyStatesQueryResults
        :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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        authorization_namespace: Literal["Microsoft.Authorization"] = kwargs.pop(
            "authorization_namespace", "Microsoft.Authorization"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-10-01"))
        cls: ClsType[_models.ComponentPolicyStatesQueryResults] = kwargs.pop("cls", None)

        _request = build_component_policy_states_list_query_results_for_resource_group_level_policy_assignment_request(
            subscription_id=subscription_id,
            resource_group_name=resource_group_name,
            policy_assignment_name=policy_assignment_name,
            component_policy_states_resource=component_policy_states_resource,
            top=top,
            order_by=order_by,
            select=select,
            from_parameter=from_parameter,
            to=to,
            filter=filter,
            apply=apply,
            authorization_namespace=authorization_namespace,
            api_version=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.ComponentPolicyStatesQueryResults, response.json())

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

        return deserialized  # type: ignore


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s
        :attr:`policy_tracked_resources` 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: PolicyInsightsClientConfiguration = 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_query_results_for_management_group(
        self,
        management_group_name: str,
        policy_tracked_resources_resource: Union[str, _models.PolicyTrackedResourcesResourceType],
        *,
        top: Optional[int] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyTrackedResource"]:
        """Queries policy tracked resources under the management group.

        :param management_group_name: Management group name. Required.
        :type management_group_name: str
        :param policy_tracked_resources_resource: The name of the virtual resource under
         PolicyTrackedResources resource type; only "default" is allowed. "default" Required.
        :type policy_tracked_resources_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of PolicyTrackedResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        management_groups_namespace: Literal["Microsoft.Management"] = kwargs.pop(
            "management_groups_namespace", "Microsoft.Management"
        )
        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview"))
        cls: ClsType[List[_models.PolicyTrackedResource]] = 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_policy_tracked_resources_list_query_results_for_management_group_request(
                    management_group_name=management_group_name,
                    policy_tracked_resources_resource=policy_tracked_resources_resource,
                    top=top,
                    filter=filter,
                    management_groups_namespace=management_groups_namespace,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyTrackedResource],
                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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_subscription(
        self,
        policy_tracked_resources_resource: Union[str, _models.PolicyTrackedResourcesResourceType],
        *,
        top: Optional[int] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyTrackedResource"]:
        """Queries policy tracked resources under the subscription.

        :param policy_tracked_resources_resource: The name of the virtual resource under
         PolicyTrackedResources resource type; only "default" is allowed. "default" Required.
        :type policy_tracked_resources_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of PolicyTrackedResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview"))
        cls: ClsType[List[_models.PolicyTrackedResource]] = 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_policy_tracked_resources_list_query_results_for_subscription_request(
                    policy_tracked_resources_resource=policy_tracked_resources_resource,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyTrackedResource],
                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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_resource_group(
        self,
        resource_group_name: str,
        policy_tracked_resources_resource: Union[str, _models.PolicyTrackedResourcesResourceType],
        *,
        top: Optional[int] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyTrackedResource"]:
        """Queries policy tracked resources under the resource group.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param policy_tracked_resources_resource: The name of the virtual resource under
         PolicyTrackedResources resource type; only "default" is allowed. "default" Required.
        :type policy_tracked_resources_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of PolicyTrackedResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview"))
        cls: ClsType[List[_models.PolicyTrackedResource]] = 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_policy_tracked_resources_list_query_results_for_resource_group_request(
                    resource_group_name=resource_group_name,
                    policy_tracked_resources_resource=policy_tracked_resources_resource,
                    subscription_id=self._config.subscription_id,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyTrackedResource],
                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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list_query_results_for_resource(
        self,
        resource_id: str,
        policy_tracked_resources_resource: Union[str, _models.PolicyTrackedResourcesResourceType],
        *,
        top: Optional[int] = None,
        filter: Optional[str] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.PolicyTrackedResource"]:
        """Queries policy tracked resources under the resource.

        :param resource_id: Resource ID. Required.
        :type resource_id: str
        :param policy_tracked_resources_resource: The name of the virtual resource under
         PolicyTrackedResources resource type; only "default" is allowed. "default" Required.
        :type policy_tracked_resources_resource: str or
         ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType
        :keyword top: Maximum number of records to return. Default value is None.
        :paramtype top: int
        :keyword filter: OData filter expression. Default value is None.
        :paramtype filter: str
        :return: An iterator like instance of PolicyTrackedResource
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview"))
        cls: ClsType[List[_models.PolicyTrackedResource]] = 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_policy_tracked_resources_list_query_results_for_resource_request(
                    resource_id=resource_id,
                    policy_tracked_resources_resource=policy_tracked_resources_resource,
                    top=top,
                    filter=filter,
                    api_version=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:
                _request = HttpRequest("GET", next_link, headers=_headers)
                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.PolicyTrackedResource],
                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.QueryFailure,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)
