# 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, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.aio.client.models.v1_app_armor_profile import V1AppArmorProfile
from kubernetes.aio.client.models.v1_capabilities import V1Capabilities
from kubernetes.aio.client.models.v1_se_linux_options import V1SELinuxOptions
from kubernetes.aio.client.models.v1_seccomp_profile import V1SeccompProfile
from kubernetes.aio.client.models.v1_windows_security_context_options import V1WindowsSecurityContextOptions
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 V1SecurityContext(BaseModel):
    """
    SecurityContext holds security configuration that will be applied to a container. Some fields are present in both SecurityContext and PodSecurityContext.  When both are set, the values in SecurityContext take precedence.

    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
    allow_privilege_escalation: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("allowPrivilegeEscalation", "allow_privilege_escalation"), serialization_alias="allowPrivilegeEscalation", description="AllowPrivilegeEscalation controls whether a process can gain more privileges than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is: 1) run as Privileged 2) has CAP_SYS_ADMIN Note that this field cannot be set when spec.os.name is windows.")
    app_armor_profile: Optional[V1AppArmorProfile] = Field(default=None, validation_alias=AliasChoices("appArmorProfile", "app_armor_profile"), serialization_alias="appArmorProfile")
    capabilities: Optional[V1Capabilities] = None
    privileged: Optional[StrictBool] = Field(default=None, description="Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false. Note that this field cannot be set when spec.os.name is windows.")
    proc_mount: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("procMount", "proc_mount"), serialization_alias="procMount", description="procMount denotes the type of proc mount to use for the containers. The default value is Default which uses the container runtime defaults for readonly paths and masked paths. Note that this field cannot be set when spec.os.name is windows.")
    read_only_root_filesystem: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("readOnlyRootFilesystem", "read_only_root_filesystem"), serialization_alias="readOnlyRootFilesystem", description="Whether this container has a read-only root filesystem. Default is false. Note that this field cannot be set when spec.os.name is windows.")
    run_as_group: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("runAsGroup", "run_as_group"), serialization_alias="runAsGroup", description="The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in PodSecurityContext.  If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.")
    run_as_non_root: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("runAsNonRoot", "run_as_non_root"), serialization_alias="runAsNonRoot", description="Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext.  If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.")
    run_as_user: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("runAsUser", "run_as_user"), serialization_alias="runAsUser", description="The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext.  If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.")
    se_linux_options: Optional[V1SELinuxOptions] = Field(default=None, validation_alias=AliasChoices("seLinuxOptions", "se_linux_options"), serialization_alias="seLinuxOptions")
    seccomp_profile: Optional[V1SeccompProfile] = Field(default=None, validation_alias=AliasChoices("seccompProfile", "seccomp_profile"), serialization_alias="seccompProfile")
    windows_options: Optional[V1WindowsSecurityContextOptions] = Field(default=None, validation_alias=AliasChoices("windowsOptions", "windows_options"), serialization_alias="windowsOptions")
    openapi_types: ClassVar[Dict[str, str]] = {
        "allow_privilege_escalation": "bool",
        "app_armor_profile": "V1AppArmorProfile",
        "capabilities": "V1Capabilities",
        "privileged": "bool",
        "proc_mount": "str",
        "read_only_root_filesystem": "bool",
        "run_as_group": "int",
        "run_as_non_root": "bool",
        "run_as_user": "int",
        "se_linux_options": "V1SELinuxOptions",
        "seccomp_profile": "V1SeccompProfile",
        "windows_options": "V1WindowsSecurityContextOptions"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "allow_privilege_escalation": "allowPrivilegeEscalation",
        "app_armor_profile": "appArmorProfile",
        "capabilities": "capabilities",
        "privileged": "privileged",
        "proc_mount": "procMount",
        "read_only_root_filesystem": "readOnlyRootFilesystem",
        "run_as_group": "runAsGroup",
        "run_as_non_root": "runAsNonRoot",
        "run_as_user": "runAsUser",
        "se_linux_options": "seLinuxOptions",
        "seccomp_profile": "seccompProfile",
        "windows_options": "windowsOptions"
    }
    __properties: ClassVar[List[str]] = ["allowPrivilegeEscalation", "appArmorProfile", "capabilities", "privileged", "procMount", "readOnlyRootFilesystem", "runAsGroup", "runAsNonRoot", "runAsUser", "seLinuxOptions", "seccompProfile", "windowsOptions"]

    @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 "allowPrivilegeEscalation" not in obj and "allow_privilege_escalation" in obj:
            obj["allowPrivilegeEscalation"] = obj["allow_privilege_escalation"]
        obj.pop("allow_privilege_escalation", None)
        if "appArmorProfile" not in obj and "app_armor_profile" in obj:
            obj["appArmorProfile"] = obj["app_armor_profile"]
        obj.pop("app_armor_profile", None)
        if "procMount" not in obj and "proc_mount" in obj:
            obj["procMount"] = obj["proc_mount"]
        obj.pop("proc_mount", None)
        if "readOnlyRootFilesystem" not in obj and "read_only_root_filesystem" in obj:
            obj["readOnlyRootFilesystem"] = obj["read_only_root_filesystem"]
        obj.pop("read_only_root_filesystem", None)
        if "runAsGroup" not in obj and "run_as_group" in obj:
            obj["runAsGroup"] = obj["run_as_group"]
        obj.pop("run_as_group", None)
        if "runAsNonRoot" not in obj and "run_as_non_root" in obj:
            obj["runAsNonRoot"] = obj["run_as_non_root"]
        obj.pop("run_as_non_root", None)
        if "runAsUser" not in obj and "run_as_user" in obj:
            obj["runAsUser"] = obj["run_as_user"]
        obj.pop("run_as_user", None)
        if "seLinuxOptions" not in obj and "se_linux_options" in obj:
            obj["seLinuxOptions"] = obj["se_linux_options"]
        obj.pop("se_linux_options", None)
        if "seccompProfile" not in obj and "seccomp_profile" in obj:
            obj["seccompProfile"] = obj["seccomp_profile"]
        obj.pop("seccomp_profile", None)
        if "windowsOptions" not in obj and "windows_options" in obj:
            obj["windowsOptions"] = obj["windows_options"]
        obj.pop("windows_options", 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, V1SecurityContext):
            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, V1SecurityContext):
            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 V1SecurityContext 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 {
            ("allowPrivilegeEscalation" if serialize else "allow_privilege_escalation"): _to_legacy_value(getattr(self, "allow_privilege_escalation", None), serialize),
            ("appArmorProfile" if serialize else "app_armor_profile"): _to_legacy_value(getattr(self, "app_armor_profile", None), serialize),
            ("capabilities" if serialize else "capabilities"): _to_legacy_value(getattr(self, "capabilities", None), serialize),
            ("privileged" if serialize else "privileged"): _to_legacy_value(getattr(self, "privileged", None), serialize),
            ("procMount" if serialize else "proc_mount"): _to_legacy_value(getattr(self, "proc_mount", None), serialize),
            ("readOnlyRootFilesystem" if serialize else "read_only_root_filesystem"): _to_legacy_value(getattr(self, "read_only_root_filesystem", None), serialize),
            ("runAsGroup" if serialize else "run_as_group"): _to_legacy_value(getattr(self, "run_as_group", None), serialize),
            ("runAsNonRoot" if serialize else "run_as_non_root"): _to_legacy_value(getattr(self, "run_as_non_root", None), serialize),
            ("runAsUser" if serialize else "run_as_user"): _to_legacy_value(getattr(self, "run_as_user", None), serialize),
            ("seLinuxOptions" if serialize else "se_linux_options"): _to_legacy_value(getattr(self, "se_linux_options", None), serialize),
            ("seccompProfile" if serialize else "seccomp_profile"): _to_legacy_value(getattr(self, "seccomp_profile", None), serialize),
            ("windowsOptions" if serialize else "windows_options"): _to_legacy_value(getattr(self, "windows_options", 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 app_armor_profile
        if self.app_armor_profile:
            _dict['appArmorProfile'] = _to_openapi_value(self.app_armor_profile)
        # override the default output from pydantic by calling `to_dict()` of capabilities
        if self.capabilities:
            _dict['capabilities'] = _to_openapi_value(self.capabilities)
        # override the default output from pydantic by calling `to_dict()` of se_linux_options
        if self.se_linux_options:
            _dict['seLinuxOptions'] = _to_openapi_value(self.se_linux_options)
        # override the default output from pydantic by calling `to_dict()` of seccomp_profile
        if self.seccomp_profile:
            _dict['seccompProfile'] = _to_openapi_value(self.seccomp_profile)
        # override the default output from pydantic by calling `to_dict()` of windows_options
        if self.windows_options:
            _dict['windowsOptions'] = _to_openapi_value(self.windows_options)
        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 V1SecurityContext 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({
            "allowPrivilegeEscalation": obj.get("allowPrivilegeEscalation"),
            "appArmorProfile": V1AppArmorProfile.from_dict(obj["appArmorProfile"]) if obj.get("appArmorProfile") is not None else None,
            "capabilities": V1Capabilities.from_dict(obj["capabilities"]) if obj.get("capabilities") is not None else None,
            "privileged": obj.get("privileged"),
            "procMount": obj.get("procMount"),
            "readOnlyRootFilesystem": obj.get("readOnlyRootFilesystem"),
            "runAsGroup": obj.get("runAsGroup"),
            "runAsNonRoot": obj.get("runAsNonRoot"),
            "runAsUser": obj.get("runAsUser"),
            "seLinuxOptions": V1SELinuxOptions.from_dict(obj["seLinuxOptions"]) if obj.get("seLinuxOptions") is not None else None,
            "seccompProfile": V1SeccompProfile.from_dict(obj["seccompProfile"]) if obj.get("seccompProfile") is not None else None,
            "windowsOptions": V1WindowsSecurityContextOptions.from_dict(obj["windowsOptions"]) if obj.get("windowsOptions") is not None else None
        })
        return _obj
