# 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, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union, cast as _cast
from typing_extensions import Annotated
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 V1PodCertificateRequestSpec(BaseModel):
    """
    PodCertificateRequestSpec describes the certificate request.  All fields are immutable after creation.

    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
    max_expiration_seconds: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("maxExpirationSeconds", "max_expiration_seconds"), serialization_alias="maxExpirationSeconds", description="maxExpirationSeconds is the maximum lifetime permitted for the certificate.  If omitted, kube-apiserver will set it to 86400(24 hours). kube-apiserver will reject values shorter than 3600 (1 hour).  The maximum allowable value is 7862400 (91 days).  The signer implementation is then free to issue a certificate with any lifetime *shorter* than MaxExpirationSeconds, but no shorter than 3600 seconds (1 hour).  This constraint is enforced by kube-apiserver. `kubernetes.io` signers will never issue certificates with a lifetime longer than 24 hours.")
    node_name: StrictStr = Field(validation_alias=AliasChoices("nodeName", "node_name"), serialization_alias="nodeName", description="nodeName is the name of the node the pod is assigned to.")
    node_uid: StrictStr = Field(validation_alias=AliasChoices("nodeUID", "node_uid"), serialization_alias="nodeUID", description="nodeUID is the UID of the node the pod is assigned to.")
    pod_name: StrictStr = Field(validation_alias=AliasChoices("podName", "pod_name"), serialization_alias="podName", description="podName is the name of the pod into which the certificate will be mounted.")
    pod_uid: StrictStr = Field(validation_alias=AliasChoices("podUID", "pod_uid"), serialization_alias="podUID", description="podUID is the UID of the pod into which the certificate will be mounted.")
    service_account_name: StrictStr = Field(validation_alias=AliasChoices("serviceAccountName", "service_account_name"), serialization_alias="serviceAccountName", description="serviceAccountName is the name of the service account the pod is running as.")
    service_account_uid: StrictStr = Field(validation_alias=AliasChoices("serviceAccountUID", "service_account_uid"), serialization_alias="serviceAccountUID", description="serviceAccountUID is the UID of the service account the pod is running as.")
    signer_name: StrictStr = Field(validation_alias=AliasChoices("signerName", "signer_name"), serialization_alias="signerName", description="signerName indicates the requested signer.  All signer names beginning with `kubernetes.io` are reserved for use by the Kubernetes project.  There is currently one well-known signer documented by the Kubernetes project, `kubernetes.io/kube-apiserver-client-pod`, which will issue client certificates understood by kube-apiserver.  It is currently unimplemented.")
    stub_pkcs10_request: Union[Annotated[bytes, Field(strict=True)], Annotated[str, Field(strict=True)]] = Field(validation_alias=AliasChoices("stubPKCS10Request", "stub_pkcs10_request"), serialization_alias="stubPKCS10Request", description="A PKCS#10 certificate signing request (DER-serialized) generated by Kubelet using the subject private key.  Most signer implementations will ignore the contents of the CSR except to extract the subject public key. The API server automatically verifies the CSR signature during admission, so the signer does not need to repeat the verification.  CSRs generated by kubelet are completely empty.  The subject public key must be one of RSA3072, RSA4096, ECDSAP256, ECDSAP384, ECDSAP521, or ED25519. Note that this list may be expanded in the future.  Signer implementations do not need to support all key types supported by kube-apiserver and kubelet.  If a signer does not support the key type used for a given PodCertificateRequest, it must deny the request by setting a status.conditions entry with a type of \"Denied\" and a reason of \"UnsupportedKeyType\". It may also suggest a key type that it does support in the message field.")
    unverified_user_annotations: Optional[Dict[str, StrictStr]] = Field(default=None, validation_alias=AliasChoices("unverifiedUserAnnotations", "unverified_user_annotations"), serialization_alias="unverifiedUserAnnotations", description="unverifiedUserAnnotations allow pod authors to pass additional information to the signer implementation.  Kubernetes does not restrict or validate this metadata in any way.  Entries are subject to the same validation as object metadata annotations, with the addition that all keys must be domain-prefixed. No restrictions are placed on values, except an overall size limitation on the entire field.  Signers should document the keys and values they support.  Signers should deny requests that contain keys they do not recognize.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "max_expiration_seconds": "int",
        "node_name": "str",
        "node_uid": "str",
        "pod_name": "str",
        "pod_uid": "str",
        "service_account_name": "str",
        "service_account_uid": "str",
        "signer_name": "str",
        "stub_pkcs10_request": "bytes",
        "unverified_user_annotations": "Dict[str, str]"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "max_expiration_seconds": "maxExpirationSeconds",
        "node_name": "nodeName",
        "node_uid": "nodeUID",
        "pod_name": "podName",
        "pod_uid": "podUID",
        "service_account_name": "serviceAccountName",
        "service_account_uid": "serviceAccountUID",
        "signer_name": "signerName",
        "stub_pkcs10_request": "stubPKCS10Request",
        "unverified_user_annotations": "unverifiedUserAnnotations"
    }
    __properties: ClassVar[List[str]] = ["maxExpirationSeconds", "nodeName", "nodeUID", "podName", "podUID", "serviceAccountName", "serviceAccountUID", "signerName", "stubPKCS10Request", "unverifiedUserAnnotations"]

    @field_validator('stub_pkcs10_request', mode="before")
    def stub_pkcs10_request_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if isinstance(value, str) and not re.match(r"^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$", value):
            raise ValueError(r"must validate the regular expression /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/")
        return value

    @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 "maxExpirationSeconds" not in obj and "max_expiration_seconds" in obj:
            obj["maxExpirationSeconds"] = obj["max_expiration_seconds"]
        obj.pop("max_expiration_seconds", None)
        if "nodeName" not in obj and "node_name" in obj:
            obj["nodeName"] = obj["node_name"]
        obj.pop("node_name", None)
        if "nodeUID" not in obj and "node_uid" in obj:
            obj["nodeUID"] = obj["node_uid"]
        obj.pop("node_uid", None)
        if "podName" not in obj and "pod_name" in obj:
            obj["podName"] = obj["pod_name"]
        obj.pop("pod_name", None)
        if "podUID" not in obj and "pod_uid" in obj:
            obj["podUID"] = obj["pod_uid"]
        obj.pop("pod_uid", None)
        if "serviceAccountName" not in obj and "service_account_name" in obj:
            obj["serviceAccountName"] = obj["service_account_name"]
        obj.pop("service_account_name", None)
        if "serviceAccountUID" not in obj and "service_account_uid" in obj:
            obj["serviceAccountUID"] = obj["service_account_uid"]
        obj.pop("service_account_uid", None)
        if "signerName" not in obj and "signer_name" in obj:
            obj["signerName"] = obj["signer_name"]
        obj.pop("signer_name", None)
        if "stubPKCS10Request" not in obj and "stub_pkcs10_request" in obj:
            obj["stubPKCS10Request"] = obj["stub_pkcs10_request"]
        obj.pop("stub_pkcs10_request", None)
        if "unverifiedUserAnnotations" not in obj and "unverified_user_annotations" in obj:
            obj["unverifiedUserAnnotations"] = obj["unverified_user_annotations"]
        obj.pop("unverified_user_annotations", 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, V1PodCertificateRequestSpec):
            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, V1PodCertificateRequestSpec):
            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 V1PodCertificateRequestSpec 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 {
            ("maxExpirationSeconds" if serialize else "max_expiration_seconds"): _to_legacy_value(getattr(self, "max_expiration_seconds", None), serialize),
            ("nodeName" if serialize else "node_name"): _to_legacy_value(getattr(self, "node_name", None), serialize),
            ("nodeUID" if serialize else "node_uid"): _to_legacy_value(getattr(self, "node_uid", None), serialize),
            ("podName" if serialize else "pod_name"): _to_legacy_value(getattr(self, "pod_name", None), serialize),
            ("podUID" if serialize else "pod_uid"): _to_legacy_value(getattr(self, "pod_uid", None), serialize),
            ("serviceAccountName" if serialize else "service_account_name"): _to_legacy_value(getattr(self, "service_account_name", None), serialize),
            ("serviceAccountUID" if serialize else "service_account_uid"): _to_legacy_value(getattr(self, "service_account_uid", None), serialize),
            ("signerName" if serialize else "signer_name"): _to_legacy_value(getattr(self, "signer_name", None), serialize),
            ("stubPKCS10Request" if serialize else "stub_pkcs10_request"): _to_legacy_value(getattr(self, "stub_pkcs10_request", None), serialize),
            ("unverifiedUserAnnotations" if serialize else "unverified_user_annotations"): _to_legacy_value(getattr(self, "unverified_user_annotations", 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,
        )
        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 V1PodCertificateRequestSpec 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({
            "maxExpirationSeconds": obj.get("maxExpirationSeconds"),
            "nodeName": obj.get("nodeName"),
            "nodeUID": obj.get("nodeUID"),
            "podName": obj.get("podName"),
            "podUID": obj.get("podUID"),
            "serviceAccountName": obj.get("serviceAccountName"),
            "serviceAccountUID": obj.get("serviceAccountUID"),
            "signerName": obj.get("signerName"),
            "stubPKCS10Request": obj.get("stubPKCS10Request"),
            "unverifiedUserAnnotations": obj.get("unverifiedUserAnnotations")
        })
        return _obj
