# --------------------------------------------------------------------------------------------
# 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 aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


@register_command(
    "policy exemption create",
)
class Create(AAZCommand):
    """Create a policy exemption.

    Create a policy exemption with the given name and scope. Policy exemptions apply to all resources contained within their scope. For example, when you create a policy exemption at resource group scope for a policy assignment at the same or higher scope level, the exemption exempts all applicable resources in the resource group from applying to that policy assignment.

    :example: Create a policy exemption in default subscription
        az policy exemption create -n exemptTestVM --policy-assignment "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments/limitVMSku" --exemption-category "Waiver"

    :example: Create a policy exemption in the resource group
        az policy exemption create -n exemptTestVM --policy-assignment "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments/limitVMSku" --exemption-category "Waiver" --resource-group "myResourceGroup"

    :example: Create a policy exemption in a management group
        az policy exemption create -n exemptTestVM --policy-assignment "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyAssignments/limitVMSku" --exemption-category "Waiver" --scope "/providers/Microsoft.Management/managementGroups/{managementGroupName}"
    """

    _aaz_info = {
        "version": "2026-01-01-preview",
        "resources": [
            ["mgmt-plane", "/{scope}/providers/microsoft.authorization/policyexemptions/{}", "2026-01-01-preview"],
        ]
    }

    def _handler(self, command_args):
        super()._handler(command_args)
        self._execute_operations()
        return self._output()

    _args_schema = None

    @classmethod
    def _build_arguments_schema(cls, *args, **kwargs):
        if cls._args_schema is not None:
            return cls._args_schema
        cls._args_schema = super()._build_arguments_schema(*args, **kwargs)

        # define Arg Group ""

        _args_schema = cls._args_schema
        _args_schema.name = AAZStrArg(
            options=["-n", "--name"],
            help="The name of the policy exemption.",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[^<>%&:\\?/]*[^<>%&:\\?/ ]+$",
            ),
        )
        _args_schema.scope = AAZStrArg(
            options=["--scope"],
            help={"short-summary": "The scope of the policy assignment.", "long-summary": "Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. The scope of an assignment is always the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. If scope is not provided, the scope will be the implied or specified subscription."},
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.assignment_scope_validation = AAZStrArg(
            options=["-v", "--assignment-scope-validation"],
            arg_group="Properties",
            help={"short-summary": "The assignment scope validation", "long-summary": "Indicates the type of validation to perform on the assignment scope. Valid values are Default, DoNotValidate."},
            default="Default",
            enum={"Default": "Default", "DoNotValidate": "DoNotValidate"},
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            arg_group="Properties",
            help={"short-summary": "Policy exemption description.", "long-summary": "Full description of the policy exemption."},
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            arg_group="Properties",
            help={"short-summary": "The display name of the policy exemption.", "long-summary": "The display name of the policy exemption is not part of its ID, allowing for longer and more flexible naming."},
        )
        _args_schema.exemption_category = AAZStrArg(
            options=["-e", "--exemption-category"],
            arg_group="Properties",
            help={"short-summary": "The policy exemption category.", "long-summary": "The policy exemption category. Possible values are Mitigated and Waiver."},
            enum={"Mitigated": "Mitigated", "Waiver": "Waiver"},
        )
        _args_schema.expires_on = AAZDateTimeArg(
            options=["--expires-on"],
            arg_group="Properties",
            help={"short-summary": "The expiration date and time.", "long-summary": "The expiration date and time of the policy exemption in UTC ISO 8601 format, e.g. yyyy-MM-ddTHH:mm:ssZ."},
            fmt=AAZDateTimeFormat(
                protocol="iso",
            ),
        )
        _args_schema.metadata = AAZAnyTypeArg(
            options=["--metadata"],
            arg_group="Properties",
            help={"short-summary": "The policy exemption metadata.", "long-summary": "The policy exemption metadata. Metadata is an open-ended object and is typically a collection of key value pairs."},
        )
        _args_schema.policy_assignment = AAZStrArg(
            options=["-a", "--policy-assignment"],
            arg_group="Properties",
            help={"short-summary": "The policy assignment to exempt.", "long-summary": "The resource ID of the policy assignment to exempt."},
        )
        _args_schema.policy_definition_reference_ids = AAZListArg(
            options=["-r", "--policy-definition-reference-ids"],
            arg_group="Properties",
            help={"short-summary": "The policy definition reference IDs.", "long-summary": "The collection of policy definition reference IDs to exempt when the policy assignment is an assignment of a policy set definition."},
        )
        _args_schema.resource_selectors = AAZListArg(
            options=["--resource-selectors"],
            arg_group="Properties",
            help={"short-summary": "The resource selectors list to filter policies by resource properties.", "long-summary": "The collection of resource selector expressions used to filter policy exemption applicability by certain resource property values."},
        )

        policy_definition_reference_ids = cls._args_schema.policy_definition_reference_ids
        policy_definition_reference_ids.Element = AAZStrArg()

        resource_selectors = cls._args_schema.resource_selectors
        resource_selectors.Element = AAZObjectArg()

        _element = cls._args_schema.resource_selectors.Element
        _element.name = AAZStrArg(
            options=["name"],
            help="The name of the resource selector.",
        )
        _element.selectors = AAZListArg(
            options=["selectors"],
            help="The list of the selector expressions.",
        )

        selectors = cls._args_schema.resource_selectors.Element.selectors
        selectors.Element = AAZObjectArg()

        _element = cls._args_schema.resource_selectors.Element.selectors.Element
        _element.in_ = AAZListArg(
            options=["in"],
            help="The list of values to filter in.",
        )
        _element.kind = AAZStrArg(
            options=["kind"],
            help="The selector kind.",
            enum={"groupPrincipalId": "groupPrincipalId", "policyDefinitionReferenceId": "policyDefinitionReferenceId", "resourceLocation": "resourceLocation", "resourceType": "resourceType", "resourceWithoutLocation": "resourceWithoutLocation", "userPrincipalId": "userPrincipalId"},
        )
        _element.not_in = AAZListArg(
            options=["not-in"],
            help="The list of values to filter out.",
        )

        in_ = cls._args_schema.resource_selectors.Element.selectors.Element.in_
        in_.Element = AAZStrArg()

        not_in = cls._args_schema.resource_selectors.Element.selectors.Element.not_in
        not_in.Element = AAZStrArg()
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.PolicyExemptionsCreateOrUpdate(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    def _output(self, *args, **kwargs):
        result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)
        return result

    class PolicyExemptionsCreateOrUpdate(AAZHttpOperation):
        CLIENT_TYPE = "MgmtClient"

        def __call__(self, *args, **kwargs):
            request = self.make_request()
            session = self.client.send_request(request=request, stream=False, **kwargs)
            if session.http_response.status_code in [200, 201]:
                return self.on_200_201(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}",
                **self.url_parameters
            )

        @property
        def method(self):
            return "PUT"

        @property
        def error_format(self):
            return "MgmtErrorFormat"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "policyExemptionName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "scope", self.ctx.args.scope,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2026-01-01-preview",
                    required=True,
                ),
            }
            return parameters

        @property
        def header_parameters(self):
            parameters = {
                **self.serialize_header_param(
                    "Content-Type", "application/json",
                ),
                **self.serialize_header_param(
                    "Accept", "application/json",
                ),
            }
            return parameters

        @property
        def content(self):
            _content_value, _builder = self.new_content_builder(
                self.ctx.args,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"required": True, "client_flatten": True}}
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("assignmentScopeValidation", AAZStrType, ".assignment_scope_validation")
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("displayName", AAZStrType, ".display_name")
                properties.set_prop("exemptionCategory", AAZStrType, ".exemption_category", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("expiresOn", AAZStrType, ".expires_on")
                properties.set_prop("metadata", AAZAnyType, ".metadata")
                properties.set_prop("policyAssignmentId", AAZStrType, ".policy_assignment", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("policyDefinitionReferenceIds", AAZListType, ".policy_definition_reference_ids")
                properties.set_prop("resourceSelectors", AAZListType, ".resource_selectors")

            policy_definition_reference_ids = _builder.get(".properties.policyDefinitionReferenceIds")
            if policy_definition_reference_ids is not None:
                policy_definition_reference_ids.set_elements(AAZStrType, ".")

            resource_selectors = _builder.get(".properties.resourceSelectors")
            if resource_selectors is not None:
                resource_selectors.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.resourceSelectors[]")
            if _elements is not None:
                _elements.set_prop("name", AAZStrType, ".name")
                _elements.set_prop("selectors", AAZListType, ".selectors")

            selectors = _builder.get(".properties.resourceSelectors[].selectors")
            if selectors is not None:
                selectors.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.resourceSelectors[].selectors[]")
            if _elements is not None:
                _elements.set_prop("in", AAZListType, ".in_")
                _elements.set_prop("kind", AAZStrType, ".kind")
                _elements.set_prop("notIn", AAZListType, ".not_in")

            in_ = _builder.get(".properties.resourceSelectors[].selectors[].in")
            if in_ is not None:
                in_.set_elements(AAZStrType, ".")

            not_in = _builder.get(".properties.resourceSelectors[].selectors[].notIn")
            if not_in is not None:
                not_in.set_elements(AAZStrType, ".")

            return self.serialize_content(_content_value)

        def on_200_201(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_200_201
            )

        _schema_on_200_201 = None

        @classmethod
        def _build_schema_on_200_201(cls):
            if cls._schema_on_200_201 is not None:
                return cls._schema_on_200_201

            cls._schema_on_200_201 = AAZObjectType()

            _schema_on_200_201 = cls._schema_on_200_201
            _schema_on_200_201.id = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.properties = AAZObjectType(
                flags={"client_flatten": True},
            )
            _schema_on_200_201.system_data = AAZObjectType(
                serialized_name="systemData",
                flags={"read_only": True},
            )
            _schema_on_200_201.type = AAZStrType(
                flags={"read_only": True},
            )

            properties = cls._schema_on_200_201.properties
            properties.assignment_scope_validation = AAZStrType(
                serialized_name="assignmentScopeValidation",
            )
            properties.description = AAZStrType()
            properties.display_name = AAZStrType(
                serialized_name="displayName",
            )
            properties.exemption_category = AAZStrType(
                serialized_name="exemptionCategory",
                flags={"required": True},
            )
            properties.expires_on = AAZStrType(
                serialized_name="expiresOn",
            )
            properties.metadata = AAZAnyType()
            properties.policy_assignment_id = AAZStrType(
                serialized_name="policyAssignmentId",
                flags={"required": True},
            )
            properties.policy_definition_reference_ids = AAZListType(
                serialized_name="policyDefinitionReferenceIds",
            )
            properties.resource_selectors = AAZListType(
                serialized_name="resourceSelectors",
            )

            policy_definition_reference_ids = cls._schema_on_200_201.properties.policy_definition_reference_ids
            policy_definition_reference_ids.Element = AAZStrType()

            resource_selectors = cls._schema_on_200_201.properties.resource_selectors
            resource_selectors.Element = AAZObjectType()

            _element = cls._schema_on_200_201.properties.resource_selectors.Element
            _element.name = AAZStrType()
            _element.selectors = AAZListType()

            selectors = cls._schema_on_200_201.properties.resource_selectors.Element.selectors
            selectors.Element = AAZObjectType()

            _element = cls._schema_on_200_201.properties.resource_selectors.Element.selectors.Element
            _element["in"] = AAZListType()
            _element.kind = AAZStrType()
            _element.not_in = AAZListType(
                serialized_name="notIn",
            )

            in_ = cls._schema_on_200_201.properties.resource_selectors.Element.selectors.Element["in"]
            in_.Element = AAZStrType()

            not_in = cls._schema_on_200_201.properties.resource_selectors.Element.selectors.Element.not_in
            not_in.Element = AAZStrType()

            system_data = cls._schema_on_200_201.system_data
            system_data.created_at = AAZStrType(
                serialized_name="createdAt",
            )
            system_data.created_by = AAZStrType(
                serialized_name="createdBy",
            )
            system_data.created_by_type = AAZStrType(
                serialized_name="createdByType",
            )
            system_data.last_modified_at = AAZStrType(
                serialized_name="lastModifiedAt",
            )
            system_data.last_modified_by = AAZStrType(
                serialized_name="lastModifiedBy",
            )
            system_data.last_modified_by_type = AAZStrType(
                serialized_name="lastModifiedByType",
            )

            return cls._schema_on_200_201


class _CreateHelper:
    """Helper class for Create"""


__all__ = ["Create"]
