# 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, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.aio.client.models.admissionregistration_v1_webhook_client_config import AdmissionregistrationV1WebhookClientConfig
from kubernetes.aio.client.models.v1_label_selector import V1LabelSelector
from kubernetes.aio.client.models.v1_match_condition import V1MatchCondition
from kubernetes.aio.client.models.v1_rule_with_operations import V1RuleWithOperations
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 V1MutatingWebhook(BaseModel):
    """
    MutatingWebhook describes an admission webhook and the resources and operations it applies to.

    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
    admission_review_versions: List[StrictStr] = Field(validation_alias=AliasChoices("admissionReviewVersions", "admission_review_versions"), serialization_alias="admissionReviewVersions", description="admissionReviewVersions is an ordered list of preferred `AdmissionReview` versions the Webhook expects. API server will try to use first version in the list which it supports. If none of the versions specified in this list supported by API server, validation will fail for this object. If a persisted webhook configuration specifies allowed versions and does not include any versions known to the API Server, calls to the webhook will fail and be subject to the failure policy.")
    client_config: AdmissionregistrationV1WebhookClientConfig = Field(validation_alias=AliasChoices("clientConfig", "client_config"), serialization_alias="clientConfig")
    failure_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("failurePolicy", "failure_policy"), serialization_alias="failurePolicy", description="failurePolicy defines how unrecognized errors from the admission endpoint are handled - allowed values are Ignore or Fail. Defaults to Fail.")
    match_conditions: Optional[List[V1MatchCondition]] = 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 sent to this webhook. Match conditions filter requests that have already been matched by the rules, namespaceSelector, and objectSelector. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.  The exact matching logic is (in order):   1. If ANY matchCondition evaluates to FALSE, the webhook is skipped.   2. If ALL matchConditions evaluate to TRUE, the webhook is called.   3. If any matchCondition evaluates to an error (but none are FALSE):      - If failurePolicy=Fail, reject the request      - If failurePolicy=Ignore, the error is ignored and the webhook is skipped")
    match_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("matchPolicy", "match_policy"), serialization_alias="matchPolicy", description="matchPolicy defines how the \"rules\" list is used to match incoming requests. Allowed values are \"Exact\" or \"Equivalent\".  - Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the webhook.  - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the webhook.  Defaults to \"Equivalent\"")
    name: StrictStr = Field(description="name is the name of the admission webhook. Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where \"imagepolicy\" is the name of the webhook, and kubernetes.io is the name of the organization. Required.")
    namespace_selector: Optional[V1LabelSelector] = Field(default=None, validation_alias=AliasChoices("namespaceSelector", "namespace_selector"), serialization_alias="namespaceSelector")
    object_selector: Optional[V1LabelSelector] = Field(default=None, validation_alias=AliasChoices("objectSelector", "object_selector"), serialization_alias="objectSelector")
    reinvocation_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("reinvocationPolicy", "reinvocation_policy"), serialization_alias="reinvocationPolicy", description="reinvocationPolicy indicates whether this webhook should be called multiple times as part of a single admission evaluation. Allowed values are \"Never\" and \"IfNeeded\".  Never: the webhook will not be called more than once in a single admission evaluation.  IfNeeded: the webhook will be called at least one additional time as part of the admission evaluation if the object being admitted is modified by other admission plugins after the initial webhook call. Webhooks that specify this option *must* be idempotent, able to process objects they previously admitted. Note: * the number of additional invocations is not guaranteed to be exactly one. * if additional invocations result in further modifications to the object, webhooks are not guaranteed to be invoked again. * webhooks that use this option may be reordered to minimize the number of additional invocations. * to validate an object after all mutations are guaranteed complete, use a validating admission webhook instead.  Defaults to \"Never\".")
    rules: Optional[List[V1RuleWithOperations]] = Field(default=None, description="rules describes what operations on what resources/subresources the webhook cares about. The webhook cares about an operation if it matches _any_ Rule. However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks from putting the cluster in a state which cannot be recovered from without completely disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.")
    side_effects: StrictStr = Field(validation_alias=AliasChoices("sideEffects", "side_effects"), serialization_alias="sideEffects", description="sideEffects states whether this webhook has side effects. Acceptable values are: None, NoneOnDryRun (webhooks created via v1beta1 may also specify Some or Unknown). Webhooks with side effects MUST implement a reconciliation system, since a request may be rejected by a future step in the admission chain and the side effects therefore need to be undone. Requests with the dryRun attribute will be auto-rejected if they match a webhook with sideEffects == Unknown or Some.")
    timeout_seconds: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("timeoutSeconds", "timeout_seconds"), serialization_alias="timeoutSeconds", description="timeoutSeconds specifies the timeout for this webhook. After the timeout passes, the webhook call will be ignored or the API call will fail based on the failure policy. The timeout value must be between 1 and 30 seconds. Default to 10 seconds.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "admission_review_versions": "List[str]",
        "client_config": "AdmissionregistrationV1WebhookClientConfig",
        "failure_policy": "str",
        "match_conditions": "List[V1MatchCondition]",
        "match_policy": "str",
        "name": "str",
        "namespace_selector": "V1LabelSelector",
        "object_selector": "V1LabelSelector",
        "reinvocation_policy": "str",
        "rules": "List[V1RuleWithOperations]",
        "side_effects": "str",
        "timeout_seconds": "int"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "admission_review_versions": "admissionReviewVersions",
        "client_config": "clientConfig",
        "failure_policy": "failurePolicy",
        "match_conditions": "matchConditions",
        "match_policy": "matchPolicy",
        "name": "name",
        "namespace_selector": "namespaceSelector",
        "object_selector": "objectSelector",
        "reinvocation_policy": "reinvocationPolicy",
        "rules": "rules",
        "side_effects": "sideEffects",
        "timeout_seconds": "timeoutSeconds"
    }
    __properties: ClassVar[List[str]] = ["admissionReviewVersions", "clientConfig", "failurePolicy", "matchConditions", "matchPolicy", "name", "namespaceSelector", "objectSelector", "reinvocationPolicy", "rules", "sideEffects", "timeoutSeconds"]

    @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 "admissionReviewVersions" not in obj and "admission_review_versions" in obj:
            obj["admissionReviewVersions"] = obj["admission_review_versions"]
        obj.pop("admission_review_versions", None)
        if "clientConfig" not in obj and "client_config" in obj:
            obj["clientConfig"] = obj["client_config"]
        obj.pop("client_config", None)
        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 "matchPolicy" not in obj and "match_policy" in obj:
            obj["matchPolicy"] = obj["match_policy"]
        obj.pop("match_policy", None)
        if "namespaceSelector" not in obj and "namespace_selector" in obj:
            obj["namespaceSelector"] = obj["namespace_selector"]
        obj.pop("namespace_selector", None)
        if "objectSelector" not in obj and "object_selector" in obj:
            obj["objectSelector"] = obj["object_selector"]
        obj.pop("object_selector", None)
        if "reinvocationPolicy" not in obj and "reinvocation_policy" in obj:
            obj["reinvocationPolicy"] = obj["reinvocation_policy"]
        obj.pop("reinvocation_policy", None)
        if "sideEffects" not in obj and "side_effects" in obj:
            obj["sideEffects"] = obj["side_effects"]
        obj.pop("side_effects", None)
        if "timeoutSeconds" not in obj and "timeout_seconds" in obj:
            obj["timeoutSeconds"] = obj["timeout_seconds"]
        obj.pop("timeout_seconds", 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, V1MutatingWebhook):
            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, V1MutatingWebhook):
            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 V1MutatingWebhook 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 {
            ("admissionReviewVersions" if serialize else "admission_review_versions"): _to_legacy_value(getattr(self, "admission_review_versions", None), serialize),
            ("clientConfig" if serialize else "client_config"): _to_legacy_value(getattr(self, "client_config", None), serialize),
            ("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),
            ("matchPolicy" if serialize else "match_policy"): _to_legacy_value(getattr(self, "match_policy", None), serialize),
            ("name" if serialize else "name"): _to_legacy_value(getattr(self, "name", None), serialize),
            ("namespaceSelector" if serialize else "namespace_selector"): _to_legacy_value(getattr(self, "namespace_selector", None), serialize),
            ("objectSelector" if serialize else "object_selector"): _to_legacy_value(getattr(self, "object_selector", None), serialize),
            ("reinvocationPolicy" if serialize else "reinvocation_policy"): _to_legacy_value(getattr(self, "reinvocation_policy", None), serialize),
            ("rules" if serialize else "rules"): _to_legacy_value(getattr(self, "rules", None), serialize),
            ("sideEffects" if serialize else "side_effects"): _to_legacy_value(getattr(self, "side_effects", None), serialize),
            ("timeoutSeconds" if serialize else "timeout_seconds"): _to_legacy_value(getattr(self, "timeout_seconds", 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 client_config
        if self.client_config:
            _dict['clientConfig'] = _to_openapi_value(self.client_config)
        # 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 namespace_selector
        if self.namespace_selector:
            _dict['namespaceSelector'] = _to_openapi_value(self.namespace_selector)
        # override the default output from pydantic by calling `to_dict()` of object_selector
        if self.object_selector:
            _dict['objectSelector'] = _to_openapi_value(self.object_selector)
        # override the default output from pydantic by calling `to_dict()` of each item in rules (list)
        _items = []
        if self.rules:
            for _item_rules in self.rules:
                _items.append(_to_openapi_value(_item_rules) if _item_rules is not None else None)
            _dict['rules'] = _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 V1MutatingWebhook 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({
            "admissionReviewVersions": obj.get("admissionReviewVersions"),
            "clientConfig": AdmissionregistrationV1WebhookClientConfig.from_dict(obj["clientConfig"]) if obj.get("clientConfig") is not None else None,
            "failurePolicy": obj.get("failurePolicy"),
            "matchConditions": [V1MatchCondition.from_dict(_item) for _item in obj["matchConditions"]] if obj.get("matchConditions") is not None else None,
            "matchPolicy": obj.get("matchPolicy"),
            "name": obj.get("name"),
            "namespaceSelector": V1LabelSelector.from_dict(obj["namespaceSelector"]) if obj.get("namespaceSelector") is not None else None,
            "objectSelector": V1LabelSelector.from_dict(obj["objectSelector"]) if obj.get("objectSelector") is not None else None,
            "reinvocationPolicy": obj.get("reinvocationPolicy"),
            "rules": [V1RuleWithOperations.from_dict(_item) for _item in obj["rules"]] if obj.get("rules") is not None else None,
            "sideEffects": obj.get("sideEffects"),
            "timeoutSeconds": obj.get("timeoutSeconds")
        })
        return _obj
