# coding: utf-8

"""
    Kubernetes

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    The version of the OpenAPI document: release-1.37
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from collections.abc import Mapping as _Mapping
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.aio.client.models.v1beta1_match_condition import V1beta1MatchCondition
from kubernetes.aio.client.models.v1beta1_match_resources import V1beta1MatchResources
from kubernetes.aio.client.models.v1beta1_mutation import V1beta1Mutation
from kubernetes.aio.client.models.v1beta1_param_kind import V1beta1ParamKind
from kubernetes.aio.client.models.v1beta1_variable import V1beta1Variable
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python


_OPENAPI_GENERATOR_TO_DICT = "_openapi_generator_to_dict"


def _get_openapi_to_dict(value: Any) -> Any:
    # Reciprocal function references preserve inherited generated methods
    # without reserving model member names. Checking both directions also
    # rejects overrides whose decorators copy function attributes.
    to_dict = getattr(value, "to_dict", None)
    type_to_dict = getattr(type(value), "to_dict", None)
    if (
        not callable(to_dict)
        or getattr(to_dict, "__func__", None) is not type_to_dict
    ):
        return None

    openapi_to_dict = getattr(
        type_to_dict, _OPENAPI_GENERATOR_TO_DICT, None
    )
    if (
        not callable(openapi_to_dict)
        or getattr(
            openapi_to_dict,
            _OPENAPI_GENERATOR_TO_DICT,
            None,
        ) is not type_to_dict
    ):
        return None
    return openapi_to_dict


def _to_legacy_item(value: Any, serialize: bool) -> Any:
    to_dict = getattr(value, "to_dict", None)
    if _get_openapi_to_dict(value) is not None and callable(to_dict):
        return to_dict(serialize=serialize)
    if callable(to_dict):
        return to_dict()
    return value


def _to_legacy_value(value: Any, serialize: bool) -> Any:
    # python-legacy converted only immediate list elements or dictionary values:
    # https://github.com/OpenAPITools/openapi-generator/blob/c84b949df1a9ec04ba75989cb49b45c940c2f694/modules/openapi-generator/src/main/resources/python-legacy/model.mustache#L203-L231
    if isinstance(value, list):
        return [_to_legacy_item(item, serialize) for item in value]
    if isinstance(value, dict):
        return {
            key: _to_legacy_item(item, serialize)
            for key, item in value.items()
        }
    return _to_legacy_item(value, serialize)


def _to_openapi_value(value: Any) -> Any:
    if isinstance(value, list):
        return [_to_openapi_value(item) for item in value]
    if isinstance(value, dict):
        return {key: _to_openapi_value(item) for key, item in value.items()}

    to_openapi_dict = _get_openapi_to_dict(value)
    if to_openapi_dict is not None:
        return to_openapi_dict(value)

    to_dict = getattr(value, "to_dict", None)
    if callable(to_dict):
        return to_dict()
    return value


class V1beta1MutatingAdmissionPolicySpec(BaseModel):
    """
    MutatingAdmissionPolicySpec is the specification of the desired behavior of the admission policy.

    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """ # noqa: E501
    failure_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("failurePolicy", "failure_policy"), serialization_alias="failurePolicy", description="failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.  A policy is invalid if paramKind refers to a non-existent Kind. A binding is invalid if paramRef.name refers to a non-existent resource.  failurePolicy does not define how validations that evaluate to false are handled.  Allowed values are Ignore or Fail. Defaults to Fail.")
    match_conditions: Optional[List[V1beta1MatchCondition]] = Field(default=None, validation_alias=AliasChoices("matchConditions", "match_conditions"), serialization_alias="matchConditions", description="matchConditions is a list of conditions that must be met for a request to be validated. Match conditions filter requests that have already been matched by the matchConstraints. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.  If a parameter object is provided, it can be accessed via the `params` handle in the same manner as validation expressions.  The exact matching logic is (in order):   1. If ANY matchCondition evaluates to FALSE, the policy is skipped.   2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.   3. If any matchCondition evaluates to an error (but none are FALSE):      - If failurePolicy=Fail, reject the request      - If failurePolicy=Ignore, the policy is skipped")
    match_constraints: Optional[V1beta1MatchResources] = Field(default=None, validation_alias=AliasChoices("matchConstraints", "match_constraints"), serialization_alias="matchConstraints")
    mutations: Optional[List[V1beta1Mutation]] = Field(default=None, description="mutations contain operations to perform on matching objects. mutations may not be empty; a minimum of one mutation is required. mutations are evaluated in order, and are reinvoked according to the reinvocationPolicy. The mutations of a policy are invoked for each binding of this policy and reinvocation of mutations occurs on a per binding basis.")
    param_kind: Optional[V1beta1ParamKind] = Field(default=None, validation_alias=AliasChoices("paramKind", "param_kind"), serialization_alias="paramKind")
    reinvocation_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("reinvocationPolicy", "reinvocation_policy"), serialization_alias="reinvocationPolicy", description="reinvocationPolicy indicates whether mutations may be called multiple times per MutatingAdmissionPolicyBinding as part of a single admission evaluation. Allowed values are \"Never\" and \"IfNeeded\".  Never: These mutations will not be called more than once per binding in a single admission evaluation.  IfNeeded: These mutations may be invoked more than once per binding for a single admission request and there is no guarantee of order with respect to other admission plugins, admission webhooks, bindings of this policy and admission policies.  Mutations are only reinvoked when mutations change the object after this mutation is invoked. Required.")
    variables: Optional[List[V1beta1Variable]] = Field(default=None, description="variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under `variables` in other expressions of the policy except matchConditions because matchConditions are evaluated before the rest of the policy.  The expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, variables must be sorted by the order of first appearance and acyclic.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "failure_policy": "str",
        "match_conditions": "List[V1beta1MatchCondition]",
        "match_constraints": "V1beta1MatchResources",
        "mutations": "List[V1beta1Mutation]",
        "param_kind": "V1beta1ParamKind",
        "reinvocation_policy": "str",
        "variables": "List[V1beta1Variable]"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "failure_policy": "failurePolicy",
        "match_conditions": "matchConditions",
        "match_constraints": "matchConstraints",
        "mutations": "mutations",
        "param_kind": "paramKind",
        "reinvocation_policy": "reinvocationPolicy",
        "variables": "variables"
    }
    __properties: ClassVar[List[str]] = ["failurePolicy", "matchConditions", "matchConstraints", "mutations", "paramKind", "reinvocationPolicy", "variables"]

    @classmethod
    def __preprocess_input_names(
        cls,
        obj: Any,
        remove_hidden_storage_names: bool = True,
    ) -> Any:
        if not isinstance(obj, _Mapping):
            return obj
        obj = dict(obj)
        if "failurePolicy" not in obj and "failure_policy" in obj:
            obj["failurePolicy"] = obj["failure_policy"]
        obj.pop("failure_policy", None)
        if "matchConditions" not in obj and "match_conditions" in obj:
            obj["matchConditions"] = obj["match_conditions"]
        obj.pop("match_conditions", None)
        if "matchConstraints" not in obj and "match_constraints" in obj:
            obj["matchConstraints"] = obj["match_constraints"]
        obj.pop("match_constraints", None)
        if "paramKind" not in obj and "param_kind" in obj:
            obj["paramKind"] = obj["param_kind"]
        obj.pop("param_kind", None)
        if "reinvocationPolicy" not in obj and "reinvocation_policy" in obj:
            obj["reinvocationPolicy"] = obj["reinvocation_policy"]
        obj.pop("reinvocation_policy", None)
        return obj

    model_config = ConfigDict(
        validate_by_name=True,
        validate_by_alias=True,
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self) -> str:
        """For print and pprint"""
        return self.to_str()

    def __eq__(self, other: object) -> bool:
        """Returns true if both objects are equal"""
        if not isinstance(other, V1beta1MutatingAdmissionPolicySpec):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other: object) -> bool:
        """Returns true if both objects are not equal"""
        if not isinstance(other, V1beta1MutatingAdmissionPolicySpec):
            return True

        return not (self == other)


    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        to_openapi_dict = _get_openapi_to_dict(self)
        if to_openapi_dict is not None:
            return json.dumps(to_jsonable_python(to_openapi_dict(self)))
        return json.dumps(to_jsonable_python(self.to_dict()))

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of V1beta1MutatingAdmissionPolicySpec from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self, serialize: bool = False) -> Dict[str, Any]:
        """Return all declared model fields using public or wire names."""
        return {
            ("failurePolicy" if serialize else "failure_policy"): _to_legacy_value(getattr(self, "failure_policy", None), serialize),
            ("matchConditions" if serialize else "match_conditions"): _to_legacy_value(getattr(self, "match_conditions", None), serialize),
            ("matchConstraints" if serialize else "match_constraints"): _to_legacy_value(getattr(self, "match_constraints", None), serialize),
            ("mutations" if serialize else "mutations"): _to_legacy_value(getattr(self, "mutations", None), serialize),
            ("paramKind" if serialize else "param_kind"): _to_legacy_value(getattr(self, "param_kind", None), serialize),
            ("reinvocationPolicy" if serialize else "reinvocation_policy"): _to_legacy_value(getattr(self, "reinvocation_policy", None), serialize),
            ("variables" if serialize else "variables"): _to_legacy_value(getattr(self, "variables", None), serialize),
        }

    def __openapi_generator_modern_projection(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in match_conditions (list)
        _items = []
        if self.match_conditions:
            for _item_match_conditions in self.match_conditions:
                _items.append(_to_openapi_value(_item_match_conditions) if _item_match_conditions is not None else None)
            _dict['matchConditions'] = _items
        # override the default output from pydantic by calling `to_dict()` of match_constraints
        if self.match_constraints:
            _dict['matchConstraints'] = _to_openapi_value(self.match_constraints)
        # override the default output from pydantic by calling `to_dict()` of each item in mutations (list)
        _items = []
        if self.mutations:
            for _item_mutations in self.mutations:
                _items.append(_to_openapi_value(_item_mutations) if _item_mutations is not None else None)
            _dict['mutations'] = _items
        # override the default output from pydantic by calling `to_dict()` of param_kind
        if self.param_kind:
            _dict['paramKind'] = _to_openapi_value(self.param_kind)
        # override the default output from pydantic by calling `to_dict()` of each item in variables (list)
        _items = []
        if self.variables:
            for _item_variables in self.variables:
                _items.append(_to_openapi_value(_item_variables) if _item_variables is not None else None)
            _dict['variables'] = _items
        return _dict

    setattr(
        to_dict,
        _OPENAPI_GENERATOR_TO_DICT,
        __openapi_generator_modern_projection,
    )
    setattr(
        __openapi_generator_modern_projection,
        _OPENAPI_GENERATOR_TO_DICT,
        to_dict,
    )
    del __openapi_generator_modern_projection

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of V1beta1MutatingAdmissionPolicySpec from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        obj = _cast(
            Dict[str, Any],
            cls.__preprocess_input_names(
                obj,
                remove_hidden_storage_names=True,
            ),
        )

        _obj = cls.model_validate({
            "failurePolicy": obj.get("failurePolicy"),
            "matchConditions": [V1beta1MatchCondition.from_dict(_item) for _item in obj["matchConditions"]] if obj.get("matchConditions") is not None else None,
            "matchConstraints": V1beta1MatchResources.from_dict(obj["matchConstraints"]) if obj.get("matchConstraints") is not None else None,
            "mutations": [V1beta1Mutation.from_dict(_item) for _item in obj["mutations"]] if obj.get("mutations") is not None else None,
            "paramKind": V1beta1ParamKind.from_dict(obj["paramKind"]) if obj.get("paramKind") is not None else None,
            "reinvocationPolicy": obj.get("reinvocationPolicy"),
            "variables": [V1beta1Variable.from_dict(_item) for _item in obj["variables"]] if obj.get("variables") is not None else None
        })
        return _obj
