# 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_se_linux_options import V1SELinuxOptions
from kubernetes.aio.client.models.v1_seccomp_profile import V1SeccompProfile
from kubernetes.aio.client.models.v1_sysctl import V1Sysctl
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 V1PodSecurityContext(BaseModel):
    """
    PodSecurityContext holds pod-level security attributes and common container settings. Some fields are also present in container.securityContext.  Field values of container.securityContext take precedence over field values of PodSecurityContext.

    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
    app_armor_profile: Optional[V1AppArmorProfile] = Field(default=None, validation_alias=AliasChoices("appArmorProfile", "app_armor_profile"), serialization_alias="appArmorProfile")
    fs_group: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("fsGroup", "fs_group"), serialization_alias="fsGroup", description="A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod:  1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw----  If unset, the Kubelet will not modify the ownership and permissions of any volume. Note that this field cannot be set when spec.os.name is windows.")
    fs_group_change_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("fsGroupChangePolicy", "fs_group_change_policy"), serialization_alias="fsGroupChangePolicy", description="fsGroupChangePolicy defines behavior of changing ownership and permission of the volume before being exposed inside Pod. This field will only apply to volume types which support fsGroup based ownership(and permissions). It will have no effect on ephemeral volume types such as: secret, configmaps and emptydir. Valid values are \"OnRootMismatch\" and \"Always\". If not specified, \"Always\" is used. 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 SecurityContext.  If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. 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 SecurityContext.  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 SecurityContext.  If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.")
    se_linux_change_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("seLinuxChangePolicy", "se_linux_change_policy"), serialization_alias="seLinuxChangePolicy", description="seLinuxChangePolicy defines how the container's SELinux label is applied to all volumes used by the Pod. It has no effect on nodes that do not support SELinux or to volumes does not support SELinux. Valid values are \"MountOption\" and \"Recursive\".  \"Recursive\" means relabeling of all files on all Pod volumes by the container runtime. This may be slow for large volumes, but allows mixing privileged and unprivileged Pods sharing the same volume on the same node.  \"MountOption\" mounts all eligible Pod volumes with `-o context` mount option. This requires all Pods that share the same volume to use the same SELinux label. It is not possible to share the same volume among privileged and unprivileged Pods. Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their CSIDriver instance. Other volumes are always re-labelled recursively.  If not specified, \"MountOption\" is used.  This field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers.  All Pods that use the same volume should use the same seLinuxChangePolicy, otherwise some pods can get stuck in ContainerCreating state. 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")
    supplemental_groups: Optional[List[StrictInt]] = Field(default=None, validation_alias=AliasChoices("supplementalGroups", "supplemental_groups"), serialization_alias="supplementalGroups", description="A list of groups applied to the first process run in each container, in addition to the container's primary GID and fsGroup (if specified).  If the SupplementalGroupsPolicy feature is enabled, the supplementalGroupsPolicy field determines whether these are in addition to or instead of any group memberships defined in the container image. If unspecified, no additional groups are added, though group memberships defined in the container image may still be used, depending on the supplementalGroupsPolicy field. Note that this field cannot be set when spec.os.name is windows.")
    supplemental_groups_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("supplementalGroupsPolicy", "supplemental_groups_policy"), serialization_alias="supplementalGroupsPolicy", description="Defines how supplemental groups of the first container processes are calculated. Valid values are \"Merge\" and \"Strict\". If not specified, \"Merge\" is used. (Alpha) Using the field requires the SupplementalGroupsPolicy feature gate to be enabled and the container runtime must implement support for this feature. Note that this field cannot be set when spec.os.name is windows.")
    sysctls: Optional[List[V1Sysctl]] = Field(default=None, description="Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch. Note that this field cannot be set when spec.os.name is windows.")
    windows_options: Optional[V1WindowsSecurityContextOptions] = Field(default=None, validation_alias=AliasChoices("windowsOptions", "windows_options"), serialization_alias="windowsOptions")
    openapi_types: ClassVar[Dict[str, str]] = {
        "app_armor_profile": "V1AppArmorProfile",
        "fs_group": "int",
        "fs_group_change_policy": "str",
        "run_as_group": "int",
        "run_as_non_root": "bool",
        "run_as_user": "int",
        "se_linux_change_policy": "str",
        "se_linux_options": "V1SELinuxOptions",
        "seccomp_profile": "V1SeccompProfile",
        "supplemental_groups": "List[int]",
        "supplemental_groups_policy": "str",
        "sysctls": "List[V1Sysctl]",
        "windows_options": "V1WindowsSecurityContextOptions"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "app_armor_profile": "appArmorProfile",
        "fs_group": "fsGroup",
        "fs_group_change_policy": "fsGroupChangePolicy",
        "run_as_group": "runAsGroup",
        "run_as_non_root": "runAsNonRoot",
        "run_as_user": "runAsUser",
        "se_linux_change_policy": "seLinuxChangePolicy",
        "se_linux_options": "seLinuxOptions",
        "seccomp_profile": "seccompProfile",
        "supplemental_groups": "supplementalGroups",
        "supplemental_groups_policy": "supplementalGroupsPolicy",
        "sysctls": "sysctls",
        "windows_options": "windowsOptions"
    }
    __properties: ClassVar[List[str]] = ["appArmorProfile", "fsGroup", "fsGroupChangePolicy", "runAsGroup", "runAsNonRoot", "runAsUser", "seLinuxChangePolicy", "seLinuxOptions", "seccompProfile", "supplementalGroups", "supplementalGroupsPolicy", "sysctls", "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 "appArmorProfile" not in obj and "app_armor_profile" in obj:
            obj["appArmorProfile"] = obj["app_armor_profile"]
        obj.pop("app_armor_profile", None)
        if "fsGroup" not in obj and "fs_group" in obj:
            obj["fsGroup"] = obj["fs_group"]
        obj.pop("fs_group", None)
        if "fsGroupChangePolicy" not in obj and "fs_group_change_policy" in obj:
            obj["fsGroupChangePolicy"] = obj["fs_group_change_policy"]
        obj.pop("fs_group_change_policy", 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 "seLinuxChangePolicy" not in obj and "se_linux_change_policy" in obj:
            obj["seLinuxChangePolicy"] = obj["se_linux_change_policy"]
        obj.pop("se_linux_change_policy", 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 "supplementalGroups" not in obj and "supplemental_groups" in obj:
            obj["supplementalGroups"] = obj["supplemental_groups"]
        obj.pop("supplemental_groups", None)
        if "supplementalGroupsPolicy" not in obj and "supplemental_groups_policy" in obj:
            obj["supplementalGroupsPolicy"] = obj["supplemental_groups_policy"]
        obj.pop("supplemental_groups_policy", 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, V1PodSecurityContext):
            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, V1PodSecurityContext):
            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 V1PodSecurityContext 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 {
            ("appArmorProfile" if serialize else "app_armor_profile"): _to_legacy_value(getattr(self, "app_armor_profile", None), serialize),
            ("fsGroup" if serialize else "fs_group"): _to_legacy_value(getattr(self, "fs_group", None), serialize),
            ("fsGroupChangePolicy" if serialize else "fs_group_change_policy"): _to_legacy_value(getattr(self, "fs_group_change_policy", 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),
            ("seLinuxChangePolicy" if serialize else "se_linux_change_policy"): _to_legacy_value(getattr(self, "se_linux_change_policy", 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),
            ("supplementalGroups" if serialize else "supplemental_groups"): _to_legacy_value(getattr(self, "supplemental_groups", None), serialize),
            ("supplementalGroupsPolicy" if serialize else "supplemental_groups_policy"): _to_legacy_value(getattr(self, "supplemental_groups_policy", None), serialize),
            ("sysctls" if serialize else "sysctls"): _to_legacy_value(getattr(self, "sysctls", 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 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 each item in sysctls (list)
        _items = []
        if self.sysctls:
            for _item_sysctls in self.sysctls:
                _items.append(_to_openapi_value(_item_sysctls) if _item_sysctls is not None else None)
            _dict['sysctls'] = _items
        # 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 V1PodSecurityContext 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({
            "appArmorProfile": V1AppArmorProfile.from_dict(obj["appArmorProfile"]) if obj.get("appArmorProfile") is not None else None,
            "fsGroup": obj.get("fsGroup"),
            "fsGroupChangePolicy": obj.get("fsGroupChangePolicy"),
            "runAsGroup": obj.get("runAsGroup"),
            "runAsNonRoot": obj.get("runAsNonRoot"),
            "runAsUser": obj.get("runAsUser"),
            "seLinuxChangePolicy": obj.get("seLinuxChangePolicy"),
            "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,
            "supplementalGroups": obj.get("supplementalGroups"),
            "supplementalGroupsPolicy": obj.get("supplementalGroupsPolicy"),
            "sysctls": [V1Sysctl.from_dict(_item) for _item in obj["sysctls"]] if obj.get("sysctls") is not None else None,
            "windowsOptions": V1WindowsSecurityContextOptions.from_dict(obj["windowsOptions"]) if obj.get("windowsOptions") is not None else None
        })
        return _obj
