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

    Create a policy definition version in the given subscription or management group with the given name and other properties.

    :example: Create a policy definition with older version
        az policy definition version create --name readOnlyStorage --rules "{ 'if': { 'field': 'type', 'equals': 'Microsoft.Storage/storageAccounts/write' }, 'then': { 'effect': 'deny' } }" --version 1.1.0
    """

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

    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="The management group.",
            fmt=AAZStrArgFormat(
                max_length=90,
                min_length=1,
            ),
        )
        _args_schema.name = AAZStrArg(
            options=["-n", "--name"],
            help="The name of the policy definition.",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[^<>%&:\\?/]*[^<>%&:\\?/ ]+$",
            ),
        )
        _args_schema.version = AAZStrArg(
            options=["--version"],
            help={"short-summary": "The policy definition version.", "long-summary": "The policy definition version in #.#.# format."},
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^\\d+\\.\\d+\\.\\d+$",
            ),
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.description = AAZStrArg(
            options=["--description"],
            arg_group="Properties",
            help="The policy definition description.",
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            arg_group="Properties",
            help="The display name of the policy definition.",
        )
        _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.",
        )
        _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."},
        )
        _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."},
            default="Indexed",
        )
        _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."},
        )
        _args_schema.rules = AAZAnyTypeArg(
            options=["--rule", "--rules"],
            arg_group="Properties",
            help="The policy rule.",
        )

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

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

        role_definition_ids = cls._args_schema.external_evaluation_enforcement_settings.role_definition_ids
        role_definition_ids.Element = AAZStrArg()

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

        _element = cls._args_schema.params.Element
        _element.allowed_values = AAZListArg(
            options=["allowed-values"],
            help="The allowed values for the parameter.",
        )
        _element.default_value = AAZAnyTypeArg(
            options=["default-value"],
            help="The default value for the parameter if no value is provided.",
        )
        _element.metadata = AAZFreeFormDictArg(
            options=["metadata"],
            help="General metadata for the parameter.",
        )
        _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/.",
        )
        _element.type = AAZStrArg(
            options=["type"],
            help="The data type of the parameter.",
            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()
        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) and has_value(self.ctx.args.version)
        condition_1 = has_value(self.ctx.args.name) and has_value(self.ctx.args.version) and has_value(self.ctx.subscription_id)
        if condition_0:
            self.PolicyDefinitionVersionsCreateOrUpdateAtManagementGroup(ctx=self.ctx)()
        if condition_1:
            self.PolicyDefinitionVersionsCreateOrUpdate(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 PolicyDefinitionVersionsCreateOrUpdateAtManagementGroup(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(
                "/providers/Microsoft.Management/managementGroups/{managementGroupName}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}",
                **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(
                    "managementGroupName", self.ctx.args.management_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "policyDefinitionName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "policyDefinitionVersion", self.ctx.args.version,
                    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,
                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("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")

            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 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.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()

            external_evaluation_enforcement_settings = cls._schema_on_200_201.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 = cls._schema_on_200_201.properties.external_evaluation_enforcement_settings.endpoint_settings
            endpoint_settings.details = AAZAnyType()
            endpoint_settings.kind = AAZStrType()

            role_definition_ids = cls._schema_on_200_201.properties.external_evaluation_enforcement_settings.role_definition_ids
            role_definition_ids.Element = AAZStrType()

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

            _element = cls._schema_on_200_201.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 = cls._schema_on_200_201.properties.parameters.Element.allowed_values
            allowed_values.Element = AAZAnyType()

            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 PolicyDefinitionVersionsCreateOrUpdate(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(
                "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}/versions/{policyDefinitionVersion}",
                **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(
                    "policyDefinitionVersion", self.ctx.args.version,
                    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,
                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("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")

            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 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.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()

            external_evaluation_enforcement_settings = cls._schema_on_200_201.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 = cls._schema_on_200_201.properties.external_evaluation_enforcement_settings.endpoint_settings
            endpoint_settings.details = AAZAnyType()
            endpoint_settings.kind = AAZStrType()

            role_definition_ids = cls._schema_on_200_201.properties.external_evaluation_enforcement_settings.role_definition_ids
            role_definition_ids.Element = AAZStrType()

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

            _element = cls._schema_on_200_201.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 = cls._schema_on_200_201.properties.parameters.Element.allowed_values
            allowed_values.Element = AAZAnyType()

            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"]
