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

from azure.core import PipelineClient
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    StreamClosedError,
    StreamConsumedError,
    map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.rest import HttpRequest, HttpResponse
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling

from .. import models as _models
from .._configuration import ManagementGroupsMgmtClientConfiguration
from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize
from .._utils.serialization import Deserializer, Serializer
from .._utils.utils import ClientMixinABC

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

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False


def build_operations_list_request(**kwargs: Any) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/operations"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_get_request(
    group_id: str,
    *,
    expand: Optional[Union[str, _models.ManagementGroupExpandType]] = None,
    recurse: Optional[bool] = None,
    filter: Optional[str] = None,
    cache_control: str = "no-cache",
    **kwargs: Any,
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if expand is not None:
        _params["$expand"] = _SERIALIZER.query("expand", expand, "str")
    if recurse is not None:
        _params["$recurse"] = _SERIALIZER.query("recurse", recurse, "bool")
    if filter is not None:
        _params["$filter"] = _SERIALIZER.query("filter", filter, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_create_or_update_request(  # pylint: disable=name-too-long
    group_id: str, *, cache_control: str = "no-cache", **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_update_request(
    group_id: str, *, cache_control: str = "no-cache", **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_delete_request(
    group_id: str, *, cache_control: str = "no-cache", **kwargs: Any
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_get_descendants_request(  # pylint: disable=name-too-long
    group_id: str, *, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/descendants"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if skiptoken is not None:
        _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str")
    if top is not None:
        _params["$top"] = _SERIALIZER.query("top", top, "int")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_list_request(
    *, cache_control: str = "no-cache", skiptoken: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if skiptoken is not None:
        _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_hierarchy_settings_list_request(group_id: str, **kwargs: Any) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/settings"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_hierarchy_settings_get_request(group_id: str, **kwargs: Any) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_hierarchy_settings_create_or_update_request(  # pylint: disable=name-too-long
    group_id: str, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)


def build_hierarchy_settings_update_request(group_id: str, **kwargs: Any) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs)


def build_hierarchy_settings_delete_request(group_id: str, **kwargs: Any) -> HttpRequest:
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01"))
    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs)


def build_management_group_subscriptions_get_subscription_request(  # pylint: disable=name-too-long
    group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_group_subscriptions_create_request(  # pylint: disable=name-too-long
    group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_group_subscriptions_delete_request(  # pylint: disable=name-too-long
    group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
) -> HttpRequest:
    _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", "2023-04-01"))
    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_group_subscriptions_get_subscriptions_under_management_group_request(  # pylint: disable=name-too-long
    group_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions"
    path_format_arguments = {
        "groupId": _SERIALIZER.url("group_id", group_id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if skiptoken is not None:
        _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_entities_list_request(
    *,
    skiptoken: Optional[str] = None,
    skip: Optional[int] = None,
    top: Optional[int] = None,
    select: Optional[str] = None,
    search: Optional[Union[str, _models.EntitySearchType]] = None,
    filter: Optional[str] = None,
    view: Optional[Union[str, _models.EntityViewParameterType]] = None,
    group_name: Optional[str] = None,
    cache_control: str = "no-cache",
    **kwargs: Any,
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/getEntities"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if skiptoken is not None:
        _params["$skiptoken"] = _SERIALIZER.query("skiptoken", skiptoken, "str")
    if skip is not None:
        _params["$skip"] = _SERIALIZER.query("skip", skip, "int")
    if top is not None:
        _params["$top"] = _SERIALIZER.query("top", top, "int")
    if select is not None:
        _params["$select"] = _SERIALIZER.query("select", select, "str")
    if search is not None:
        _params["$search"] = _SERIALIZER.query("search", search, "str")
    if filter is not None:
        _params["$filter"] = _SERIALIZER.query("filter", filter, "str")
    if view is not None:
        _params["$view"] = _SERIALIZER.query("view", view, "str")
    if group_name is not None:
        _params["groupName"] = _SERIALIZER.query("group_name", group_name, "str")

    # Construct headers
    if cache_control is not None:
        _headers["Cache-Control"] = _SERIALIZER.header("cache_control", cache_control, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_mgmt_check_name_availability_request(  # pylint: disable=name-too-long
    **kwargs: Any,
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/checkNameAvailability"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_mgmt_start_tenant_backfill_request(  # pylint: disable=name-too-long
    **kwargs: Any,
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/startTenantBackfill"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


def build_management_groups_mgmt_tenant_backfill_status_request(  # pylint: disable=name-too-long
    **kwargs: Any,
) -> HttpRequest:
    _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", "2023-04-01"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/providers/Microsoft.Management/tenantBackfillStatus"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


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

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

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

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

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

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

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

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

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

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

            return _request

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

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

            _stream = False
            pipeline_response: PipelineResponse = 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 ItemPaged(get_next, extract_data)


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.ManagementGroupsMgmtClient`'s
        :attr:`management_groups` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ManagementGroupsMgmtClientConfiguration = (
            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 get(
        self,
        group_id: str,
        *,
        expand: Optional[Union[str, _models.ManagementGroupExpandType]] = None,
        recurse: Optional[bool] = None,
        filter: Optional[str] = None,
        cache_control: str = "no-cache",
        **kwargs: Any,
    ) -> _models.ManagementGroup:
        """Get the details of the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword expand: The $expand=children query string parameter allows clients to request
         inclusion of children in the response payload.  $expand=path includes the path from the root
         group to the current group.  $expand=ancestors includes the ancestor Ids of the current group.
         Known values are: "children", "path", and "ancestors". Default value is None.
        :paramtype expand: str or ~azure.mgmt.managementgroups.models.ManagementGroupExpandType
        :keyword recurse: The $recurse=true query string parameter allows clients to request inclusion
         of entire hierarchy in the response payload. Note that  $expand=children must be passed up if
         $recurse is set to true. Default value is None.
        :paramtype recurse: bool
        :keyword filter: A filter which allows the exclusion of subscriptions from results (i.e.
         '$filter=children.childType ne Subscription'). Default value is None.
        :paramtype filter: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.ManagementGroup, response.json())

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

        return deserialized  # type: ignore

    def _create_or_update_initial(
        self,
        group_id: str,
        create_management_group_request: Union[_models.CreateManagementGroupRequest, JSON, IO[bytes]],
        *,
        cache_control: str = "no-cache",
        **kwargs: Any,
    ) -> Iterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        pipeline_response: PipelineResponse = 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:
                response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

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

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

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

        return deserialized  # type: ignore

    @overload
    def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: _models.CreateManagementGroupRequest,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> LROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Required.
        :type create_management_group_request:
         ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :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 LROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: JSON,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> LROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Required.
        :type create_management_group_request: JSON
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :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 LROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: IO[bytes],
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> LROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Required.
        :type create_management_group_request: IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :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 LROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: Union[_models.CreateManagementGroupRequest, JSON, IO[bytes]],
        *,
        cache_control: str = "no-cache",
        **kwargs: Any,
    ) -> LROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Is one of the
         following types: CreateManagementGroupRequest, JSON, IO[bytes] Required.
        :type create_management_group_request:
         ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest or JSON or IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: An instance of LROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ManagementGroup] = kwargs.pop("cls", None)
        polling: Union[bool, PollingMethod] = 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 = self._create_or_update_initial(
                group_id=group_id,
                create_management_group_request=create_management_group_request,
                cache_control=cache_control,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs,
            )
            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.ManagementGroup, 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: PollingMethod = cast(
                PollingMethod, ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(PollingMethod, NoPolling())
        else:
            polling_method = polling
        if cont_token:
            return LROPoller[_models.ManagementGroup].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return LROPoller[_models.ManagementGroup](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @overload
    def update(
        self,
        group_id: str,
        patch_group_request: _models.PatchManagementGroupRequest,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Required.
        :type patch_group_request: ~azure.mgmt.managementgroups.models.PatchManagementGroupRequest
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def update(
        self,
        group_id: str,
        patch_group_request: JSON,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Required.
        :type patch_group_request: JSON
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def update(
        self,
        group_id: str,
        patch_group_request: IO[bytes],
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Required.
        :type patch_group_request: IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def update(
        self,
        group_id: str,
        patch_group_request: Union[_models.PatchManagementGroupRequest, JSON, IO[bytes]],
        *,
        cache_control: str = "no-cache",
        **kwargs: Any,
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Is one of the following types:
         PatchManagementGroupRequest, JSON, IO[bytes] Required.
        :type patch_group_request: ~azure.mgmt.managementgroups.models.PatchManagementGroupRequest or
         JSON or IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.ManagementGroup, response.json())

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

        return deserialized  # type: ignore

    def _delete_initial(self, group_id: str, *, cache_control: str = "no-cache", **kwargs: Any) -> Iterator[bytes]:
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        response = pipeline_response.http_response

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

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            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
    def begin_delete(self, group_id: str, *, cache_control: str = "no-cache", **kwargs: Any) -> LROPoller[None]:
        """Delete management group. If a management group contains child resources, the request will fail.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: An instance of LROPoller that returns None
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, PollingMethod] = 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 = self._delete_initial(
                group_id=group_id,
                cache_control=cache_control,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs,
            )
            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: PollingMethod = cast(
                PollingMethod, ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(PollingMethod, NoPolling())
        else:
            polling_method = polling
        if cont_token:
            return LROPoller[None].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method)  # type: ignore

    @distributed_trace
    def get_descendants(
        self, group_id: str, *, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any
    ) -> ItemPaged["_models.DescendantInfo"]:
        """List all entities that descend from a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :keyword top: Number of elements to return when retrieving results. Passing this in will
         override $skipToken. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of DescendantInfo
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.DescendantInfo]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DescendantInfo]] = 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_management_groups_get_descendants_request(
                    group_id=group_id,
                    skiptoken=skiptoken,
                    top=top,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

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

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

            _stream = False
            pipeline_response: PipelineResponse = 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 ItemPaged(get_next, extract_data)

    @distributed_trace
    def list(
        self, *, cache_control: str = "no-cache", skiptoken: Optional[str] = None, **kwargs: Any
    ) -> ItemPaged["_models.ManagementGroupInfo"]:
        """List management groups for the authenticated user.

        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :return: An iterator like instance of ManagementGroupInfo
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.ManagementGroupInfo]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ManagementGroupInfo]] = 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_management_groups_list_request(
                    cache_control=cache_control,
                    skiptoken=skiptoken,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

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

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

            _stream = False
            pipeline_response: PipelineResponse = 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 ItemPaged(get_next, extract_data)


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.ManagementGroupsMgmtClient`'s
        :attr:`hierarchy_settings` attribute.
    """

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

    @distributed_trace
    def list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsList:
        """Gets all the hierarchy settings defined at the Management Group level. Settings can only be set
        on the root Management Group of the hierarchy.

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

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.HierarchySettingsList, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings:
        """Gets the hierarchy settings defined at the Management Group level. Settings can only be set on
        the root Management Group of the hierarchy.

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

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.HierarchySettings, response.json())

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

        return deserialized  # type: ignore

    @overload
    def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: _models.CreateOrUpdateSettingsRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, JSON, IO[bytes]],
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Is one of the
         following types: CreateOrUpdateSettingsRequest, JSON, IO[bytes] Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or JSON or IO[bytes]
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.HierarchySettings, response.json())

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

        return deserialized  # type: ignore

    @overload
    def update(
        self,
        group_id: str,
        create_tenant_settings_request: _models.CreateOrUpdateSettingsRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def update(
        self,
        group_id: str,
        create_tenant_settings_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def update(
        self,
        group_id: str,
        create_tenant_settings_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def update(
        self,
        group_id: str,
        create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, JSON, IO[bytes]],
        **kwargs: Any,
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Is one of the
         following types: CreateOrUpdateSettingsRequest, JSON, IO[bytes] Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or JSON or IO[bytes]
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.HierarchySettings, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def delete(self, group_id: str, **kwargs: Any) -> None:  # pylint: disable=inconsistent-return-statements
        """Deletes the hierarchy settings defined at the Management Group level.

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

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

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

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

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

        response = pipeline_response.http_response

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

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


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.ManagementGroupsMgmtClient`'s
        :attr:`management_group_subscriptions` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: ManagementGroupsMgmtClientConfiguration = (
            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 get_subscription(
        self, group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> _models.SubscriptionUnderManagementGroup:
        """Retrieves details about given subscription which is associated with the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param subscription_id: Subscription ID. Required.
        :type subscription_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: SubscriptionUnderManagementGroup. The SubscriptionUnderManagementGroup is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.SubscriptionUnderManagementGroup, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def create(
        self, group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> _models.SubscriptionUnderManagementGroup:
        """Associates existing subscription with the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param subscription_id: Subscription ID. Required.
        :type subscription_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: SubscriptionUnderManagementGroup. The SubscriptionUnderManagementGroup is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.SubscriptionUnderManagementGroup, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def delete(  # pylint: disable=inconsistent-return-statements
        self, group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> None:
        """De-associates subscription from the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param subscription_id: Subscription ID. Required.
        :type subscription_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

        _stream = False
        pipeline_response: PipelineResponse = 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 get_subscriptions_under_management_group(
        self, group_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any
    ) -> ItemPaged["_models.SubscriptionUnderManagementGroup"]:
        """Retrieves details about all subscriptions which are associated with the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :return: An iterator like instance of SubscriptionUnderManagementGroup
        :rtype:
         ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SubscriptionUnderManagementGroup]] = 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_management_group_subscriptions_get_subscriptions_under_management_group_request(
                    group_id=group_id,
                    skiptoken=skiptoken,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

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

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

            _stream = False
            pipeline_response: PipelineResponse = 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 ItemPaged(get_next, extract_data)


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.ManagementGroupsMgmtClient`'s
        :attr:`entities` attribute.
    """

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

    @distributed_trace
    def list(
        self,
        *,
        skiptoken: Optional[str] = None,
        skip: Optional[int] = None,
        top: Optional[int] = None,
        select: Optional[str] = None,
        search: Optional[Union[str, _models.EntitySearchType]] = None,
        filter: Optional[str] = None,
        view: Optional[Union[str, _models.EntityViewParameterType]] = None,
        group_name: Optional[str] = None,
        cache_control: str = "no-cache",
        **kwargs: Any,
    ) -> ItemPaged["_models.EntityInfo"]:
        """List all entities (Management Groups, Subscriptions, etc.) for the authenticated user.

        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :keyword skip: Number of entities to skip over when retrieving results. Passing this in will
         override $skipToken. Default value is None.
        :paramtype skip: int
        :keyword top: Number of elements to return when retrieving results. Passing this in will
         override $skipToken. Default value is None.
        :paramtype top: int
        :keyword select: This parameter specifies the fields to include in the response. Can include
         any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g.
         '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the
         $select parameter can override select in $skipToken. Default value is None.
        :paramtype select: str
        :keyword search: The $search parameter is used in conjunction with the $filter parameter to
         return three different outputs depending on the parameter passed in.
         With $search=AllowedParents the API will return the entity info of all groups that the
         requested entity will be able to reparent to as determined by the user's permissions.
         With $search=AllowedChildren the API will return the entity info of all entities that can be
         added as children of the requested entity.
         With $search=ParentAndFirstLevelChildren the API will return the parent and  first level of
         children that the user has either direct access to or indirect access via one of their
         descendants.
         With $search=ParentOnly the API will return only the group if the user has access to at least
         one of the descendants of the group.
         With $search=ChildrenOnly the API will return only the first level of children of the group
         entity info specified in $filter.  The user must have direct access to the children entities or
         one of it's descendants for it to show up in the results. Known values are: "AllowedParents",
         "AllowedChildren", "ParentAndFirstLevelChildren", "ParentOnly", and "ChildrenOnly". Default
         value is None.
        :paramtype search: str or ~azure.mgmt.managementgroups.models.EntitySearchType
        :keyword filter: The filter parameter allows you to filter on the the name or display name
         fields. You can check for equality on the name field (e.g. name eq '{entityName}')  and you can
         check for substrings on either the name or display name fields(e.g. contains(name,
         '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the
         '{entityName}' and '{substringToSearch}' fields are checked case insensitively. Default value
         is None.
        :paramtype filter: str
        :keyword view: The view parameter allows clients to filter the type of data that is returned by
         the getEntities call. Known values are: "FullHierarchy", "GroupsOnly", "SubscriptionsOnly", and
         "Audit". Default value is None.
        :paramtype view: str or ~azure.mgmt.managementgroups.models.EntityViewParameterType
        :keyword group_name: A filter which allows the get entities call to focus on a particular group
         (i.e. "$filter=name eq 'groupName'"). Default value is None.
        :paramtype group_name: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: An iterator like instance of EntityInfo
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.managementgroups.models.EntityInfo]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.EntityInfo]] = 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_entities_list_request(
                    skiptoken=skiptoken,
                    skip=skip,
                    top=top,
                    select=select,
                    search=search,
                    filter=filter,
                    view=view,
                    group_name=group_name,
                    cache_control=cache_control,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

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

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

            _stream = False
            pipeline_response: PipelineResponse = 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 ItemPaged(get_next, extract_data)


class _ManagementGroupsMgmtClientOperationsMixin(
    ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], ManagementGroupsMgmtClientConfiguration]
):

    @overload
    def check_name_availability(
        self,
        check_name_availability_request: _models.CheckNameAvailabilityRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any,
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

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

    @overload
    def check_name_availability(
        self, check_name_availability_request: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

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

    @overload
    def check_name_availability(
        self, check_name_availability_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

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

    @distributed_trace
    def check_name_availability(
        self,
        check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]],
        **kwargs: Any,
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

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

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

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.CheckNameAvailabilityResult, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillStatusResult:
        """Starts backfilling subscriptions for the Tenant.

        :return: TenantBackfillStatusResult. The TenantBackfillStatusResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.TenantBackfillStatusResult, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace
    def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillStatusResult:
        """Gets tenant backfill status.

        :return: TenantBackfillStatusResult. The TenantBackfillStatusResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("stream", False)
        pipeline_response: PipelineResponse = 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:
                    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.TenantBackfillStatusResult, response.json())

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

        return deserialized  # type: ignore
