# 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 datetime import datetime
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.client.models.v1_managed_fields_entry import V1ManagedFieldsEntry
from kubernetes.client.models.v1_owner_reference import V1OwnerReference
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 V1ObjectMeta(BaseModel):
    """
    ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.

    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
    annotations: Optional[Dict[str, StrictStr]] = Field(default=None, description="Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations")
    creation_timestamp: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("creationTimestamp", "creation_timestamp"), serialization_alias="creationTimestamp", description="CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.  Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata")
    deletion_grace_period_seconds: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("deletionGracePeriodSeconds", "deletion_grace_period_seconds"), serialization_alias="deletionGracePeriodSeconds", description="Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.")
    deletion_timestamp: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("deletionTimestamp", "deletion_timestamp"), serialization_alias="deletionTimestamp", description="DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.  Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata")
    finalizers: Optional[List[StrictStr]] = Field(default=None, description="Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order.  Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list.")
    generate_name: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("generateName", "generate_name"), serialization_alias="generateName", description="GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.  If this field is specified and the generated name exists, the server will return a 409.  Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency")
    generation: Optional[StrictInt] = Field(default=None, description="A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.")
    labels: Optional[Dict[str, StrictStr]] = Field(default=None, description="Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels")
    managed_fields: Optional[List[V1ManagedFieldsEntry]] = Field(default=None, validation_alias=AliasChoices("managedFields", "managed_fields"), serialization_alias="managedFields", description="ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like \"ci-cd\". The set of fields is always in the version that the workflow used when modifying the object.")
    name: Optional[StrictStr] = Field(default=None, description="Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names")
    namespace: Optional[StrictStr] = Field(default=None, description="Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.  Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces")
    owner_references: Optional[List[V1OwnerReference]] = Field(default=None, validation_alias=AliasChoices("ownerReferences", "owner_references"), serialization_alias="ownerReferences", description="List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.")
    resource_version: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("resourceVersion", "resource_version"), serialization_alias="resourceVersion", description="An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.  Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency")
    self_link: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("selfLink", "self_link"), serialization_alias="selfLink", description="Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.")
    uid: Optional[StrictStr] = Field(default=None, description="UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.  Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids")
    openapi_types: ClassVar[Dict[str, str]] = {
        "annotations": "Dict[str, str]",
        "creation_timestamp": "datetime",
        "deletion_grace_period_seconds": "int",
        "deletion_timestamp": "datetime",
        "finalizers": "List[str]",
        "generate_name": "str",
        "generation": "int",
        "labels": "Dict[str, str]",
        "managed_fields": "List[V1ManagedFieldsEntry]",
        "name": "str",
        "namespace": "str",
        "owner_references": "List[V1OwnerReference]",
        "resource_version": "str",
        "self_link": "str",
        "uid": "str"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "annotations": "annotations",
        "creation_timestamp": "creationTimestamp",
        "deletion_grace_period_seconds": "deletionGracePeriodSeconds",
        "deletion_timestamp": "deletionTimestamp",
        "finalizers": "finalizers",
        "generate_name": "generateName",
        "generation": "generation",
        "labels": "labels",
        "managed_fields": "managedFields",
        "name": "name",
        "namespace": "namespace",
        "owner_references": "ownerReferences",
        "resource_version": "resourceVersion",
        "self_link": "selfLink",
        "uid": "uid"
    }
    __properties: ClassVar[List[str]] = ["annotations", "creationTimestamp", "deletionGracePeriodSeconds", "deletionTimestamp", "finalizers", "generateName", "generation", "labels", "managedFields", "name", "namespace", "ownerReferences", "resourceVersion", "selfLink", "uid"]

    @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 "creationTimestamp" not in obj and "creation_timestamp" in obj:
            obj["creationTimestamp"] = obj["creation_timestamp"]
        obj.pop("creation_timestamp", None)
        if "deletionGracePeriodSeconds" not in obj and "deletion_grace_period_seconds" in obj:
            obj["deletionGracePeriodSeconds"] = obj["deletion_grace_period_seconds"]
        obj.pop("deletion_grace_period_seconds", None)
        if "deletionTimestamp" not in obj and "deletion_timestamp" in obj:
            obj["deletionTimestamp"] = obj["deletion_timestamp"]
        obj.pop("deletion_timestamp", None)
        if "generateName" not in obj and "generate_name" in obj:
            obj["generateName"] = obj["generate_name"]
        obj.pop("generate_name", None)
        if "managedFields" not in obj and "managed_fields" in obj:
            obj["managedFields"] = obj["managed_fields"]
        obj.pop("managed_fields", None)
        if "ownerReferences" not in obj and "owner_references" in obj:
            obj["ownerReferences"] = obj["owner_references"]
        obj.pop("owner_references", None)
        if "resourceVersion" not in obj and "resource_version" in obj:
            obj["resourceVersion"] = obj["resource_version"]
        obj.pop("resource_version", None)
        if "selfLink" not in obj and "self_link" in obj:
            obj["selfLink"] = obj["self_link"]
        obj.pop("self_link", 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, V1ObjectMeta):
            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, V1ObjectMeta):
            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 V1ObjectMeta 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 {
            ("annotations" if serialize else "annotations"): _to_legacy_value(getattr(self, "annotations", None), serialize),
            ("creationTimestamp" if serialize else "creation_timestamp"): _to_legacy_value(getattr(self, "creation_timestamp", None), serialize),
            ("deletionGracePeriodSeconds" if serialize else "deletion_grace_period_seconds"): _to_legacy_value(getattr(self, "deletion_grace_period_seconds", None), serialize),
            ("deletionTimestamp" if serialize else "deletion_timestamp"): _to_legacy_value(getattr(self, "deletion_timestamp", None), serialize),
            ("finalizers" if serialize else "finalizers"): _to_legacy_value(getattr(self, "finalizers", None), serialize),
            ("generateName" if serialize else "generate_name"): _to_legacy_value(getattr(self, "generate_name", None), serialize),
            ("generation" if serialize else "generation"): _to_legacy_value(getattr(self, "generation", None), serialize),
            ("labels" if serialize else "labels"): _to_legacy_value(getattr(self, "labels", None), serialize),
            ("managedFields" if serialize else "managed_fields"): _to_legacy_value(getattr(self, "managed_fields", None), serialize),
            ("name" if serialize else "name"): _to_legacy_value(getattr(self, "name", None), serialize),
            ("namespace" if serialize else "namespace"): _to_legacy_value(getattr(self, "namespace", None), serialize),
            ("ownerReferences" if serialize else "owner_references"): _to_legacy_value(getattr(self, "owner_references", None), serialize),
            ("resourceVersion" if serialize else "resource_version"): _to_legacy_value(getattr(self, "resource_version", None), serialize),
            ("selfLink" if serialize else "self_link"): _to_legacy_value(getattr(self, "self_link", None), serialize),
            ("uid" if serialize else "uid"): _to_legacy_value(getattr(self, "uid", 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 managed_fields (list)
        _items = []
        if self.managed_fields:
            for _item_managed_fields in self.managed_fields:
                _items.append(_to_openapi_value(_item_managed_fields) if _item_managed_fields is not None else None)
            _dict['managedFields'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in owner_references (list)
        _items = []
        if self.owner_references:
            for _item_owner_references in self.owner_references:
                _items.append(_to_openapi_value(_item_owner_references) if _item_owner_references is not None else None)
            _dict['ownerReferences'] = _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 V1ObjectMeta 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({
            "annotations": obj.get("annotations"),
            "creationTimestamp": obj.get("creationTimestamp"),
            "deletionGracePeriodSeconds": obj.get("deletionGracePeriodSeconds"),
            "deletionTimestamp": obj.get("deletionTimestamp"),
            "finalizers": obj.get("finalizers"),
            "generateName": obj.get("generateName"),
            "generation": obj.get("generation"),
            "labels": obj.get("labels"),
            "managedFields": [V1ManagedFieldsEntry.from_dict(_item) for _item in obj["managedFields"]] if obj.get("managedFields") is not None else None,
            "name": obj.get("name"),
            "namespace": obj.get("namespace"),
            "ownerReferences": [V1OwnerReference.from_dict(_item) for _item in obj["ownerReferences"]] if obj.get("ownerReferences") is not None else None,
            "resourceVersion": obj.get("resourceVersion"),
            "selfLink": obj.get("selfLink"),
            "uid": obj.get("uid")
        })
        return _obj
