# 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, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union, cast as _cast
from typing_extensions import Annotated
from kubernetes.aio.client.models.apiregistration_v1_service_reference import ApiregistrationV1ServiceReference
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 V1APIServiceSpec(BaseModel):
    """
    APIServiceSpec contains information for locating and communicating with a server. Only https is supported, though you are able to disable certificate verification.

    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
    ca_bundle: Optional[Union[Annotated[bytes, Field(strict=True)], Annotated[str, Field(strict=True)]]] = Field(default=None, validation_alias=AliasChoices("caBundle", "ca_bundle"), serialization_alias="caBundle", description="CABundle is a PEM encoded CA bundle which will be used to validate an API server's serving certificate. If unspecified, system trust roots on the apiserver are used.")
    group: Optional[StrictStr] = Field(default=None, description="Group is the API group name this server hosts")
    group_priority_minimum: StrictInt = Field(validation_alias=AliasChoices("groupPriorityMinimum", "group_priority_minimum"), serialization_alias="groupPriorityMinimum", description="GroupPriorityMinimum is the priority this group should have at least. Higher priority means that the group is preferred by clients over lower priority ones. Note that other versions of this group might specify even higher GroupPriorityMinimum values such that the whole group gets a higher priority. The primary sort is based on GroupPriorityMinimum, ordered highest number to lowest (20 before 10). The secondary sort is based on the alphabetical comparison of the name of the object.  (v1.bar before v1.foo) We'd recommend something like: *.k8s.io (except extensions) at 18000 and PaaSes (OpenShift, Deis) are recommended to be in the 2000s")
    insecure_skip_tls_verify: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("insecureSkipTLSVerify", "insecure_skip_tls_verify"), serialization_alias="insecureSkipTLSVerify", description="InsecureSkipTLSVerify disables TLS certificate verification when communicating with this server. This is strongly discouraged.  You should use the CABundle instead.")
    service: Optional[ApiregistrationV1ServiceReference] = None
    version: Optional[StrictStr] = Field(default=None, description="Version is the API version this server hosts.  For example, \"v1\"")
    version_priority: StrictInt = Field(validation_alias=AliasChoices("versionPriority", "version_priority"), serialization_alias="versionPriority", description="VersionPriority controls the ordering of this API version inside of its group.  Must be greater than zero. The primary sort is based on VersionPriority, ordered highest to lowest (20 before 10). Since it's inside of a group, the number can be small, probably in the 10s. In case of equal version priorities, the version string will be used to compute the order inside a group. If the version string is \"kube-like\", it will sort above non \"kube-like\" version strings, which are ordered lexicographically. \"Kube-like\" versions start with a \"v\", then are followed by a number (the major version), then optionally the string \"alpha\" or \"beta\" and another number (the minor version). These are sorted first by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing major version, then minor version. An example sorted list of versions: v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "ca_bundle": "bytes",
        "group": "str",
        "group_priority_minimum": "int",
        "insecure_skip_tls_verify": "bool",
        "service": "ApiregistrationV1ServiceReference",
        "version": "str",
        "version_priority": "int"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "ca_bundle": "caBundle",
        "group": "group",
        "group_priority_minimum": "groupPriorityMinimum",
        "insecure_skip_tls_verify": "insecureSkipTLSVerify",
        "service": "service",
        "version": "version",
        "version_priority": "versionPriority"
    }
    __properties: ClassVar[List[str]] = ["caBundle", "group", "groupPriorityMinimum", "insecureSkipTLSVerify", "service", "version", "versionPriority"]

    @field_validator('ca_bundle', mode="before")
    def ca_bundle_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        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 "caBundle" not in obj and "ca_bundle" in obj:
            obj["caBundle"] = obj["ca_bundle"]
        obj.pop("ca_bundle", None)
        if "groupPriorityMinimum" not in obj and "group_priority_minimum" in obj:
            obj["groupPriorityMinimum"] = obj["group_priority_minimum"]
        obj.pop("group_priority_minimum", None)
        if "insecureSkipTLSVerify" not in obj and "insecure_skip_tls_verify" in obj:
            obj["insecureSkipTLSVerify"] = obj["insecure_skip_tls_verify"]
        obj.pop("insecure_skip_tls_verify", None)
        if "versionPriority" not in obj and "version_priority" in obj:
            obj["versionPriority"] = obj["version_priority"]
        obj.pop("version_priority", 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, V1APIServiceSpec):
            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, V1APIServiceSpec):
            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 V1APIServiceSpec 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 {
            ("caBundle" if serialize else "ca_bundle"): _to_legacy_value(getattr(self, "ca_bundle", None), serialize),
            ("group" if serialize else "group"): _to_legacy_value(getattr(self, "group", None), serialize),
            ("groupPriorityMinimum" if serialize else "group_priority_minimum"): _to_legacy_value(getattr(self, "group_priority_minimum", None), serialize),
            ("insecureSkipTLSVerify" if serialize else "insecure_skip_tls_verify"): _to_legacy_value(getattr(self, "insecure_skip_tls_verify", None), serialize),
            ("service" if serialize else "service"): _to_legacy_value(getattr(self, "service", None), serialize),
            ("version" if serialize else "version"): _to_legacy_value(getattr(self, "version", None), serialize),
            ("versionPriority" if serialize else "version_priority"): _to_legacy_value(getattr(self, "version_priority", 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 service
        if self.service:
            _dict['service'] = _to_openapi_value(self.service)
        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 V1APIServiceSpec 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({
            "caBundle": obj.get("caBundle"),
            "group": obj.get("group"),
            "groupPriorityMinimum": obj.get("groupPriorityMinimum"),
            "insecureSkipTLSVerify": obj.get("insecureSkipTLSVerify"),
            "service": ApiregistrationV1ServiceReference.from_dict(obj["service"]) if obj.get("service") is not None else None,
            "version": obj.get("version"),
            "versionPriority": obj.get("versionPriority")
        })
        return _obj
