# 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_job_scheduling_configuration import V1JobSchedulingConfiguration
from kubernetes.aio.client.models.v1_label_selector import V1LabelSelector
from kubernetes.aio.client.models.v1_pod_failure_policy import V1PodFailurePolicy
from kubernetes.aio.client.models.v1_pod_template_spec import V1PodTemplateSpec
from kubernetes.aio.client.models.v1_success_policy import V1SuccessPolicy
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 V1JobSpec(BaseModel):
    """
    JobSpec describes how the job execution will look like.

    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
    active_deadline_seconds: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("activeDeadlineSeconds", "active_deadline_seconds"), serialization_alias="activeDeadlineSeconds", description="Specifies the duration in seconds relative to the startTime that the job may be continuously active before the system tries to terminate it; value must be positive integer. If a Job is suspended (at creation or through an update), this timer will effectively be stopped and reset when the Job is resumed again.")
    backoff_limit: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("backoffLimit", "backoff_limit"), serialization_alias="backoffLimit", description="Specifies the number of retries before marking this job failed. Defaults to 6, unless backoffLimitPerIndex (only Indexed Job) is specified. When backoffLimitPerIndex is specified, backoffLimit defaults to 2147483647.")
    backoff_limit_per_index: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("backoffLimitPerIndex", "backoff_limit_per_index"), serialization_alias="backoffLimitPerIndex", description="Specifies the limit for the number of retries within an index before marking this index as failed. When enabled the number of failures per index is kept in the pod's batch.kubernetes.io/job-index-failure-count annotation. It can only be set when Job's completionMode=Indexed, and the Pod's restart policy is Never. The field is immutable.")
    completion_mode: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("completionMode", "completion_mode"), serialization_alias="completionMode", description="completionMode specifies how Pod completions are tracked. It can be `NonIndexed` (default) or `Indexed`.  `NonIndexed` means that the Job is considered complete when there have been .spec.completions successfully completed Pods. Each Pod completion is homologous to each other.  `Indexed` means that the Pods of a Job get an associated completion index from 0 to (.spec.completions - 1), available in the annotation batch.kubernetes.io/job-completion-index. The Job is considered complete when there is one successfully completed Pod for each index. When value is `Indexed`, .spec.completions must be specified and `.spec.parallelism` must be less than or equal to 10^5. In addition, The Pod name takes the form `$(job-name)-$(index)-$(random-string)`, the Pod hostname takes the form `$(job-name)-$(index)`.  More completion modes can be added in the future. If the Job controller observes a mode that it doesn't recognize, which is possible during upgrades due to version skew, the controller skips updates for the Job.")
    completions: Optional[StrictInt] = Field(default=None, description="Specifies the desired number of successfully finished pods the job should be run with.  Setting to null means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value.  Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/")
    managed_by: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("managedBy", "managed_by"), serialization_alias="managedBy", description="ManagedBy field indicates the controller that manages a Job. The k8s Job controller reconciles jobs which don't have this field at all or the field value is the reserved string `kubernetes.io/job-controller`, but skips reconciling Jobs with a custom value for this field. The value must be a valid domain-prefixed path (e.g. acme.io/foo) - all characters before the first \"/\" must be a valid subdomain as defined by RFC 1123. All characters trailing the first \"/\" must be valid HTTP Path characters as defined by RFC 3986. The value cannot exceed 63 characters. This field is immutable.")
    manual_selector: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("manualSelector", "manual_selector"), serialization_alias="manualSelector", description="manualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template.  When true, the user is responsible for picking unique labels and specifying the selector.  Failure to pick a unique label may cause this and other jobs to not function correctly.  However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#specifying-your-own-pod-selector")
    max_failed_indexes: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("maxFailedIndexes", "max_failed_indexes"), serialization_alias="maxFailedIndexes", description="Specifies the maximal number of failed indexes before marking the Job as failed, when backoffLimitPerIndex is set. Once the number of failed indexes exceeds this number the entire Job is marked as Failed and its execution is terminated. When left as null the job continues execution of all of its indexes and is marked with the `Complete` Job condition. It can only be specified when backoffLimitPerIndex is set. It can be null or up to completions. It is required and must be less than or equal to 10^4 when is completions greater than 10^5.")
    parallelism: Optional[StrictInt] = Field(default=None, description="Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/")
    pod_failure_policy: Optional[V1PodFailurePolicy] = Field(default=None, validation_alias=AliasChoices("podFailurePolicy", "pod_failure_policy"), serialization_alias="podFailurePolicy")
    pod_replacement_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("podReplacementPolicy", "pod_replacement_policy"), serialization_alias="podReplacementPolicy", description="podReplacementPolicy specifies when to create replacement Pods. Possible values are: - TerminatingOrFailed means that we recreate pods   when they are terminating (has a metadata.deletionTimestamp) or failed. - Failed means to wait until a previously created Pod is fully terminated (has phase   Failed or Succeeded) before creating a replacement Pod.  When using podFailurePolicy, Failed is the the only allowed value. TerminatingOrFailed and Failed are allowed values when podFailurePolicy is not in use.")
    scheduling: Optional[V1JobSchedulingConfiguration] = None
    selector: Optional[V1LabelSelector] = None
    success_policy: Optional[V1SuccessPolicy] = Field(default=None, validation_alias=AliasChoices("successPolicy", "success_policy"), serialization_alias="successPolicy")
    suspend: Optional[StrictBool] = Field(default=None, description="suspend specifies whether the Job controller should create Pods or not. If a Job is created with suspend set to true, no Pods are created by the Job controller. If a Job is suspended after creation (i.e. the flag goes from false to true), the Job controller will delete all active Pods associated with this Job. Users must design their workload to gracefully handle this. Suspending a Job will reset the StartTime field of the Job, effectively resetting the ActiveDeadlineSeconds timer too. Defaults to false.")
    template: V1PodTemplateSpec
    ttl_seconds_after_finished: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("ttlSecondsAfterFinished", "ttl_seconds_after_finished"), serialization_alias="ttlSecondsAfterFinished", description="ttlSecondsAfterFinished limits the lifetime of a Job that has finished execution (either Complete or Failed). If this field is set, ttlSecondsAfterFinished after the Job finishes, it is eligible to be automatically deleted. When the Job is being deleted, its lifecycle guarantees (e.g. finalizers) will be honored. If this field is unset, the Job won't be automatically deleted. If this field is set to zero, the Job becomes eligible to be deleted immediately after it finishes.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "active_deadline_seconds": "int",
        "backoff_limit": "int",
        "backoff_limit_per_index": "int",
        "completion_mode": "str",
        "completions": "int",
        "managed_by": "str",
        "manual_selector": "bool",
        "max_failed_indexes": "int",
        "parallelism": "int",
        "pod_failure_policy": "V1PodFailurePolicy",
        "pod_replacement_policy": "str",
        "scheduling": "V1JobSchedulingConfiguration",
        "selector": "V1LabelSelector",
        "success_policy": "V1SuccessPolicy",
        "suspend": "bool",
        "template": "V1PodTemplateSpec",
        "ttl_seconds_after_finished": "int"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "active_deadline_seconds": "activeDeadlineSeconds",
        "backoff_limit": "backoffLimit",
        "backoff_limit_per_index": "backoffLimitPerIndex",
        "completion_mode": "completionMode",
        "completions": "completions",
        "managed_by": "managedBy",
        "manual_selector": "manualSelector",
        "max_failed_indexes": "maxFailedIndexes",
        "parallelism": "parallelism",
        "pod_failure_policy": "podFailurePolicy",
        "pod_replacement_policy": "podReplacementPolicy",
        "scheduling": "scheduling",
        "selector": "selector",
        "success_policy": "successPolicy",
        "suspend": "suspend",
        "template": "template",
        "ttl_seconds_after_finished": "ttlSecondsAfterFinished"
    }
    __properties: ClassVar[List[str]] = ["activeDeadlineSeconds", "backoffLimit", "backoffLimitPerIndex", "completionMode", "completions", "managedBy", "manualSelector", "maxFailedIndexes", "parallelism", "podFailurePolicy", "podReplacementPolicy", "scheduling", "selector", "successPolicy", "suspend", "template", "ttlSecondsAfterFinished"]

    @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 "activeDeadlineSeconds" not in obj and "active_deadline_seconds" in obj:
            obj["activeDeadlineSeconds"] = obj["active_deadline_seconds"]
        obj.pop("active_deadline_seconds", None)
        if "backoffLimit" not in obj and "backoff_limit" in obj:
            obj["backoffLimit"] = obj["backoff_limit"]
        obj.pop("backoff_limit", None)
        if "backoffLimitPerIndex" not in obj and "backoff_limit_per_index" in obj:
            obj["backoffLimitPerIndex"] = obj["backoff_limit_per_index"]
        obj.pop("backoff_limit_per_index", None)
        if "completionMode" not in obj and "completion_mode" in obj:
            obj["completionMode"] = obj["completion_mode"]
        obj.pop("completion_mode", None)
        if "managedBy" not in obj and "managed_by" in obj:
            obj["managedBy"] = obj["managed_by"]
        obj.pop("managed_by", None)
        if "manualSelector" not in obj and "manual_selector" in obj:
            obj["manualSelector"] = obj["manual_selector"]
        obj.pop("manual_selector", None)
        if "maxFailedIndexes" not in obj and "max_failed_indexes" in obj:
            obj["maxFailedIndexes"] = obj["max_failed_indexes"]
        obj.pop("max_failed_indexes", None)
        if "podFailurePolicy" not in obj and "pod_failure_policy" in obj:
            obj["podFailurePolicy"] = obj["pod_failure_policy"]
        obj.pop("pod_failure_policy", None)
        if "podReplacementPolicy" not in obj and "pod_replacement_policy" in obj:
            obj["podReplacementPolicy"] = obj["pod_replacement_policy"]
        obj.pop("pod_replacement_policy", None)
        if "successPolicy" not in obj and "success_policy" in obj:
            obj["successPolicy"] = obj["success_policy"]
        obj.pop("success_policy", None)
        if "ttlSecondsAfterFinished" not in obj and "ttl_seconds_after_finished" in obj:
            obj["ttlSecondsAfterFinished"] = obj["ttl_seconds_after_finished"]
        obj.pop("ttl_seconds_after_finished", 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, V1JobSpec):
            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, V1JobSpec):
            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 V1JobSpec 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 {
            ("activeDeadlineSeconds" if serialize else "active_deadline_seconds"): _to_legacy_value(getattr(self, "active_deadline_seconds", None), serialize),
            ("backoffLimit" if serialize else "backoff_limit"): _to_legacy_value(getattr(self, "backoff_limit", None), serialize),
            ("backoffLimitPerIndex" if serialize else "backoff_limit_per_index"): _to_legacy_value(getattr(self, "backoff_limit_per_index", None), serialize),
            ("completionMode" if serialize else "completion_mode"): _to_legacy_value(getattr(self, "completion_mode", None), serialize),
            ("completions" if serialize else "completions"): _to_legacy_value(getattr(self, "completions", None), serialize),
            ("managedBy" if serialize else "managed_by"): _to_legacy_value(getattr(self, "managed_by", None), serialize),
            ("manualSelector" if serialize else "manual_selector"): _to_legacy_value(getattr(self, "manual_selector", None), serialize),
            ("maxFailedIndexes" if serialize else "max_failed_indexes"): _to_legacy_value(getattr(self, "max_failed_indexes", None), serialize),
            ("parallelism" if serialize else "parallelism"): _to_legacy_value(getattr(self, "parallelism", None), serialize),
            ("podFailurePolicy" if serialize else "pod_failure_policy"): _to_legacy_value(getattr(self, "pod_failure_policy", None), serialize),
            ("podReplacementPolicy" if serialize else "pod_replacement_policy"): _to_legacy_value(getattr(self, "pod_replacement_policy", None), serialize),
            ("scheduling" if serialize else "scheduling"): _to_legacy_value(getattr(self, "scheduling", None), serialize),
            ("selector" if serialize else "selector"): _to_legacy_value(getattr(self, "selector", None), serialize),
            ("successPolicy" if serialize else "success_policy"): _to_legacy_value(getattr(self, "success_policy", None), serialize),
            ("suspend" if serialize else "suspend"): _to_legacy_value(getattr(self, "suspend", None), serialize),
            ("template" if serialize else "template"): _to_legacy_value(getattr(self, "template", None), serialize),
            ("ttlSecondsAfterFinished" if serialize else "ttl_seconds_after_finished"): _to_legacy_value(getattr(self, "ttl_seconds_after_finished", 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 pod_failure_policy
        if self.pod_failure_policy:
            _dict['podFailurePolicy'] = _to_openapi_value(self.pod_failure_policy)
        # override the default output from pydantic by calling `to_dict()` of scheduling
        if self.scheduling:
            _dict['scheduling'] = _to_openapi_value(self.scheduling)
        # override the default output from pydantic by calling `to_dict()` of selector
        if self.selector:
            _dict['selector'] = _to_openapi_value(self.selector)
        # override the default output from pydantic by calling `to_dict()` of success_policy
        if self.success_policy:
            _dict['successPolicy'] = _to_openapi_value(self.success_policy)
        # override the default output from pydantic by calling `to_dict()` of template
        if self.template:
            _dict['template'] = _to_openapi_value(self.template)
        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 V1JobSpec 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({
            "activeDeadlineSeconds": obj.get("activeDeadlineSeconds"),
            "backoffLimit": obj.get("backoffLimit"),
            "backoffLimitPerIndex": obj.get("backoffLimitPerIndex"),
            "completionMode": obj.get("completionMode"),
            "completions": obj.get("completions"),
            "managedBy": obj.get("managedBy"),
            "manualSelector": obj.get("manualSelector"),
            "maxFailedIndexes": obj.get("maxFailedIndexes"),
            "parallelism": obj.get("parallelism"),
            "podFailurePolicy": V1PodFailurePolicy.from_dict(obj["podFailurePolicy"]) if obj.get("podFailurePolicy") is not None else None,
            "podReplacementPolicy": obj.get("podReplacementPolicy"),
            "scheduling": V1JobSchedulingConfiguration.from_dict(obj["scheduling"]) if obj.get("scheduling") is not None else None,
            "selector": V1LabelSelector.from_dict(obj["selector"]) if obj.get("selector") is not None else None,
            "successPolicy": V1SuccessPolicy.from_dict(obj["successPolicy"]) if obj.get("successPolicy") is not None else None,
            "suspend": obj.get("suspend"),
            "template": V1PodTemplateSpec.from_dict(obj["template"]) if obj.get("template") is not None else None,
            "ttlSecondsAfterFinished": obj.get("ttlSecondsAfterFinished")
        })
        return _obj
