# --------------------------------------------------------------------------------------------
# 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 definition update",
)
class Update(AAZCommand):
    """Update a policy definition.

    Update the policy definition in the given subscription or management group with the given name by applying the given properties.

    :example: Update a policy definition display name
        az policy definition update --name MyPolicyDefinition --display-name "Updated display name goes here"
    """

    _aaz_info = {
        "version": "2025-11-01",
        "resources": [
            ["mgmt-plane", "/providers/microsoft.management/managementgroups/{}/providers/microsoft.authorization/policydefinitions/{}", "2025-11-01"],
            ["mgmt-plane", "/subscriptions/{}/providers/microsoft.authorization/policydefinitions/{}", "2025-11-01"],
        ]
    }

    AZ_SUPPORT_GENERIC_UPDATE = True

    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.management_group = AAZStrArg(
            options=["--management-group"],
            help={"short-summary": "The management group.", "long-summary": "The management group with the given name where the policy definition resides."},
        )
        _args_schema.name = AAZStrArg(
            options=["-n", "--name"],
            help="The name of the policy definition.",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[^<>%&:\\?/]*[^<>%&:\\?/ ]+$",
            ),
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.description = AAZStrArg(
            options=["--description"],
            arg_group="Properties",
            help={"short-summary": "Policy definition description.", "long-summary": "Full description of the policy definition."},
            nullable=True,
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            arg_group="Properties",
            help={"short-summary": "The display name of the policy definition.", "long-summary": "The display name of the policy definition is not part of its ID, allowing for longer and more flexible naming."},
            nullable=True,
        )
        _args_schema.external_evaluation_enforcement_settings = AAZObjectArg(
            options=["--external-settings", "--external-evaluation-enforcement-settings"],
            arg_group="Properties",
            help="The details of the source of external evaluation results required by the policy during enforcement evaluation.",
            nullable=True,
        )
        _args_schema.metadata = AAZAnyTypeArg(
            options=["--metadata"],
            arg_group="Properties",
            help={"short-summary": "The policy definition metadata.", "long-summary": "The policy definition metadata. Metadata is an open-ended object and is typically a collection of key value pairs."},
            nullable=True,
        )
        _args_schema.mode = AAZStrArg(
            options=["-m", "--mode"],
            arg_group="Properties",
            help={"short-summary": "The policy definition mode.", "long-summary": "The policy definition mode. Valid values for control plane policy definitions: All, Indexed. The mode 'Indexed' indicates the policy should be evaluated only for resource types that support tags and location. Some examples for data plane policy definitions: Microsoft.KeyVault.Data, Microsoft.Network.Data."},
            nullable=True,
        )
        _args_schema.params = AAZDictArg(
            options=["-p", "--params"],
            arg_group="Properties",
            help={"short-summary": "The policy rule parameter definitions.", "long-summary": "The definitions for parameters used in the policy rule. The keys are the parameter names."},
            nullable=True,
        )
        _args_schema.rules = AAZAnyTypeArg(
            options=["--rule", "--rules"],
            arg_group="Properties",
            help="The policy rule.",
            nullable=True,
        )
        _args_schema.version = AAZStrArg(
            options=["--version"],
            arg_group="Properties",
            help={"short-summary": "The policy definition version.", "long-summary": "The policy definition version in #.#.# format."},
            nullable=True,
        )

        external_evaluation_enforcement_settings = cls._args_schema.external_evaluation_enforcement_settings
        external_evaluation_enforcement_settings.endpoint_settings = AAZObjectArg(
            options=["endpoint-settings"],
            help="The settings of an external endpoint providing evaluation results.",
            nullable=True,
        )
        external_evaluation_enforcement_settings.missing_token_action = AAZStrArg(
            options=["missing-token-action"],
            help="What to do when evaluating an enforcement policy that requires an external evaluation and the token is missing. Possible values are Audit and Deny and language expressions are supported.",
            nullable=True,
        )
        external_evaluation_enforcement_settings.result_lifespan = AAZStrArg(
            options=["result-lifespan"],
            help="The lifespan of the endpoint invocation result after which it's no longer valid. Value is expected to follow the ISO 8601 duration format and language expressions are supported.",
            nullable=True,
        )
        external_evaluation_enforcement_settings.role_definition_ids = AAZListArg(
            options=["role-definition-ids"],
            help="An array of the role definition Ids the assignment's MSI will need in order to invoke the endpoint.",
            nullable=True,
        )

        endpoint_settings = cls._args_schema.external_evaluation_enforcement_settings.endpoint_settings
        endpoint_settings.details = AAZAnyTypeArg(
            options=["details"],
            help="The details of the endpoint.",
            nullable=True,
        )
        endpoint_settings.kind = AAZStrArg(
            options=["kind"],
            help="The kind of the endpoint.",
            nullable=True,
        )

        role_definition_ids = cls._args_schema.external_evaluation_enforcement_settings.role_definition_ids
        role_definition_ids.Element = AAZStrArg(
            nullable=True,
        )

        params = cls._args_schema.params
        params.Element = AAZObjectArg(
            nullable=True,
        )

        _element = cls._args_schema.params.Element
        _element.allowed_values = AAZListArg(
            options=["allowed-values"],
            help="The allowed values for the parameter.",
            nullable=True,
        )
        _element.default_value = AAZAnyTypeArg(
            options=["default-value"],
            help="The default value for the parameter if no value is provided.",
            nullable=True,
        )
        _element.metadata = AAZFreeFormDictArg(
            options=["metadata"],
            help="General metadata for the parameter.",
            nullable=True,
        )
        _element.schema = AAZAnyTypeArg(
            options=["schema"],
            help="Provides validation of parameter inputs during assignment using a self-defined JSON schema. This property is only supported for object-type parameters and follows the Json.NET Schema 2019-09 implementation. You can learn more about using schemas at https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/.",
            nullable=True,
        )
        _element.type = AAZStrArg(
            options=["type"],
            help="The data type of the parameter.",
            nullable=True,
            enum={"Array": "Array", "Boolean": "Boolean", "DateTime": "DateTime", "Float": "Float", "Integer": "Integer", "Object": "Object", "String": "String"},
        )

        allowed_values = cls._args_schema.params.Element.allowed_values
        allowed_values.Element = AAZAnyTypeArg(
            nullable=True,
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        condition_0 = has_value(self.ctx.args.management_group) and has_value(self.ctx.args.name)
        condition_1 = has_value(self.ctx.args.name) and has_value(self.ctx.subscription_id)
        condition_2 = has_value(self.ctx.args.management_group) and has_value(self.ctx.args.name)
        condition_3 = has_value(self.ctx.args.name) and has_value(self.ctx.subscription_id)
        if condition_0:
            self.PolicyDefinitionsGetAtManagementGroup(ctx=self.ctx)()
        if condition_1:
            self.PolicyDefinitionsGet(ctx=self.ctx)()
        self.pre_instance_update(self.ctx.vars.instance)
        self.InstanceUpdateByJson(ctx=self.ctx)()
        self.InstanceUpdateByGeneric(ctx=self.ctx)()
        self.post_instance_update(self.ctx.vars.instance)
        if condition_2:
            self.PolicyDefinitionsCreateOrUpdateAtManagementGroup(ctx=self.ctx)()
        if condition_3:
            self.PolicyDefinitionsCreateOrUpdate(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    @register_callback
    def pre_instance_update(self, instance):
        pass

    @register_callback
    def post_instance_update(self, instance):
        pass

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

    class PolicyDefinitionsGetAtManagementGroup(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]:
                return self.on_200(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "managementGroupId", self.ctx.args.management_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "policyDefinitionName", self.ctx.args.name,
                    required=True,
                ),
            }
            return parameters

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

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

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

        _schema_on_200 = None

        @classmethod
        def _build_schema_on_200(cls):
            if cls._schema_on_200 is not None:
                return cls._schema_on_200

            cls._schema_on_200 = AAZObjectType()
            _UpdateHelper._build_schema_policy_definition_read(cls._schema_on_200)

            return cls._schema_on_200

    class PolicyDefinitionsGet(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]:
                return self.on_200(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "policyDefinitionName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
            }
            return parameters

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

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

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

        _schema_on_200 = None

        @classmethod
        def _build_schema_on_200(cls):
            if cls._schema_on_200 is not None:
                return cls._schema_on_200

            cls._schema_on_200 = AAZObjectType()
            _UpdateHelper._build_schema_policy_definition_read(cls._schema_on_200)

            return cls._schema_on_200

    class PolicyDefinitionsCreateOrUpdateAtManagementGroup(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 [201]:
                return self.on_201(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
                **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(
                    "managementGroupId", self.ctx.args.management_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "policyDefinitionName", self.ctx.args.name,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2025-11-01",
                    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,
                value=self.ctx.vars.instance,
            )

            return self.serialize_content(_content_value)

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

        _schema_on_201 = None

        @classmethod
        def _build_schema_on_201(cls):
            if cls._schema_on_201 is not None:
                return cls._schema_on_201

            cls._schema_on_201 = AAZObjectType()
            _UpdateHelper._build_schema_policy_definition_read(cls._schema_on_201)

            return cls._schema_on_201

    class PolicyDefinitionsCreateOrUpdate(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 [201]:
                return self.on_201(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
                **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(
                    "policyDefinitionName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2025-11-01",
                    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,
                value=self.ctx.vars.instance,
            )

            return self.serialize_content(_content_value)

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

        _schema_on_201 = None

        @classmethod
        def _build_schema_on_201(cls):
            if cls._schema_on_201 is not None:
                return cls._schema_on_201

            cls._schema_on_201 = AAZObjectType()
            _UpdateHelper._build_schema_policy_definition_read(cls._schema_on_201)

            return cls._schema_on_201

    class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance(self.ctx.vars.instance)

        def _update_instance(self, instance):
            _instance_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=instance,
                typ=AAZObjectType
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("displayName", AAZStrType, ".display_name")
                properties.set_prop("externalEvaluationEnforcementSettings", AAZObjectType, ".external_evaluation_enforcement_settings")
                properties.set_prop("metadata", AAZAnyType, ".metadata")
                properties.set_prop("mode", AAZStrType, ".mode")
                properties.set_prop("parameters", AAZDictType, ".params")
                properties.set_prop("policyRule", AAZAnyType, ".rules")
                properties.set_prop("version", AAZStrType, ".version")

            external_evaluation_enforcement_settings = _builder.get(".properties.externalEvaluationEnforcementSettings")
            if external_evaluation_enforcement_settings is not None:
                external_evaluation_enforcement_settings.set_prop("endpointSettings", AAZObjectType, ".endpoint_settings")
                external_evaluation_enforcement_settings.set_prop("missingTokenAction", AAZStrType, ".missing_token_action")
                external_evaluation_enforcement_settings.set_prop("resultLifespan", AAZStrType, ".result_lifespan")
                external_evaluation_enforcement_settings.set_prop("roleDefinitionIds", AAZListType, ".role_definition_ids")

            endpoint_settings = _builder.get(".properties.externalEvaluationEnforcementSettings.endpointSettings")
            if endpoint_settings is not None:
                endpoint_settings.set_prop("details", AAZAnyType, ".details")
                endpoint_settings.set_prop("kind", AAZStrType, ".kind")

            role_definition_ids = _builder.get(".properties.externalEvaluationEnforcementSettings.roleDefinitionIds")
            if role_definition_ids is not None:
                role_definition_ids.set_elements(AAZStrType, ".")

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

            _elements = _builder.get(".properties.parameters{}")
            if _elements is not None:
                _elements.set_prop("allowedValues", AAZListType, ".allowed_values")
                _elements.set_prop("defaultValue", AAZAnyType, ".default_value")
                _elements.set_prop("metadata", AAZFreeFormDictType, ".metadata")
                _elements.set_prop("schema", AAZAnyType, ".schema")
                _elements.set_prop("type", AAZStrType, ".type")

            allowed_values = _builder.get(".properties.parameters{}.allowedValues")
            if allowed_values is not None:
                allowed_values.set_elements(AAZAnyType, ".")

            metadata = _builder.get(".properties.parameters{}.metadata")
            if metadata is not None:
                metadata.set_anytype_elements(".")

            return _instance_value

    class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance_by_generic(
                self.ctx.vars.instance,
                self.ctx.generic_update_args
            )


class _UpdateHelper:
    """Helper class for Update"""

    _schema_policy_definition_read = None

    @classmethod
    def _build_schema_policy_definition_read(cls, _schema):
        if cls._schema_policy_definition_read is not None:
            _schema.id = cls._schema_policy_definition_read.id
            _schema.name = cls._schema_policy_definition_read.name
            _schema.properties = cls._schema_policy_definition_read.properties
            _schema.system_data = cls._schema_policy_definition_read.system_data
            _schema.type = cls._schema_policy_definition_read.type
            return

        cls._schema_policy_definition_read = _schema_policy_definition_read = AAZObjectType()

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

        properties = _schema_policy_definition_read.properties
        properties.description = AAZStrType()
        properties.display_name = AAZStrType(
            serialized_name="displayName",
        )
        properties.external_evaluation_enforcement_settings = AAZObjectType(
            serialized_name="externalEvaluationEnforcementSettings",
        )
        properties.metadata = AAZAnyType()
        properties.mode = AAZStrType()
        properties.parameters = AAZDictType()
        properties.policy_rule = AAZAnyType(
            serialized_name="policyRule",
        )
        properties.policy_type = AAZStrType(
            serialized_name="policyType",
        )
        properties.version = AAZStrType()
        properties.versions = AAZListType()

        external_evaluation_enforcement_settings = _schema_policy_definition_read.properties.external_evaluation_enforcement_settings
        external_evaluation_enforcement_settings.endpoint_settings = AAZObjectType(
            serialized_name="endpointSettings",
        )
        external_evaluation_enforcement_settings.missing_token_action = AAZStrType(
            serialized_name="missingTokenAction",
        )
        external_evaluation_enforcement_settings.result_lifespan = AAZStrType(
            serialized_name="resultLifespan",
        )
        external_evaluation_enforcement_settings.role_definition_ids = AAZListType(
            serialized_name="roleDefinitionIds",
        )

        endpoint_settings = _schema_policy_definition_read.properties.external_evaluation_enforcement_settings.endpoint_settings
        endpoint_settings.details = AAZAnyType()
        endpoint_settings.kind = AAZStrType()

        role_definition_ids = _schema_policy_definition_read.properties.external_evaluation_enforcement_settings.role_definition_ids
        role_definition_ids.Element = AAZStrType()

        parameters = _schema_policy_definition_read.properties.parameters
        parameters.Element = AAZObjectType()

        _element = _schema_policy_definition_read.properties.parameters.Element
        _element.allowed_values = AAZListType(
            serialized_name="allowedValues",
        )
        _element.default_value = AAZAnyType(
            serialized_name="defaultValue",
        )
        _element.metadata = AAZFreeFormDictType()
        _element.schema = AAZAnyType()
        _element.type = AAZStrType()

        allowed_values = _schema_policy_definition_read.properties.parameters.Element.allowed_values
        allowed_values.Element = AAZAnyType()

        versions = _schema_policy_definition_read.properties.versions
        versions.Element = AAZStrType()

        system_data = _schema_policy_definition_read.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",
        )

        _schema.id = cls._schema_policy_definition_read.id
        _schema.name = cls._schema_policy_definition_read.name
        _schema.properties = cls._schema_policy_definition_read.properties
        _schema.system_data = cls._schema_policy_definition_read.system_data
        _schema.type = cls._schema_policy_definition_read.type


__all__ = ["Update"]
