# coding: utf-8

"""
    STACKIT Observability API

    API endpoints for Observability on STACKIT

    The version of the OpenAPI document: 1.1.1
    Contact: stackit-argus@mail.schwarz
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501

from __future__ import annotations

import json
import pprint
from typing import Any, ClassVar, Dict, List, Optional, Set

from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    StrictBool,
    StrictStr,
    field_validator,
)
from typing_extensions import Annotated, Self

from stackit.observability.models.basic_auth import BasicAuth
from stackit.observability.models.http_service_sd import HTTPServiceSD
from stackit.observability.models.metrics_relabel_config import MetricsRelabelConfig
from stackit.observability.models.o_auth2 import OAuth2
from stackit.observability.models.static_configs import StaticConfigs
from stackit.observability.models.tls_config import TLSConfig


class Job(BaseModel):
    """
    Job
    """  # noqa: E501

    basic_auth: Optional[BasicAuth] = Field(default=None, alias="basicAuth")
    bearer_token: Optional[Annotated[str, Field(min_length=1, strict=True)]] = Field(default=None, alias="bearerToken")
    honor_labels: Optional[StrictBool] = Field(default=False, alias="honorLabels")
    honor_time_stamps: Optional[StrictBool] = Field(default=False, alias="honorTimeStamps")
    http_sd_configs: Optional[List[HTTPServiceSD]] = Field(default=None, alias="httpSdConfigs")
    job_name: Annotated[str, Field(min_length=1, strict=True, max_length=200)] = Field(alias="jobName")
    metrics_path: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=200)]] = Field(
        default="/metrics", alias="metricsPath"
    )
    metrics_relabel_configs: Optional[List[MetricsRelabelConfig]] = Field(default=None, alias="metricsRelabelConfigs")
    oauth2: Optional[OAuth2] = None
    params: Optional[
        Dict[
            str, Annotated[List[Annotated[str, Field(min_length=1, strict=True, max_length=200)]], Field(max_length=5)]
        ]
    ] = None
    sample_limit: Optional[Annotated[int, Field(le=1000000000, strict=True, ge=1)]] = Field(
        default=None, alias="sampleLimit"
    )
    scheme: Optional[StrictStr] = "http"
    scrape_interval: Annotated[str, Field(min_length=2, strict=True, max_length=8)] = Field(alias="scrapeInterval")
    scrape_timeout: Annotated[str, Field(min_length=2, strict=True, max_length=8)] = Field(alias="scrapeTimeout")
    static_configs: List[StaticConfigs] = Field(alias="staticConfigs")
    tls_config: Optional[TLSConfig] = Field(default=None, alias="tlsConfig")
    __properties: ClassVar[List[str]] = [
        "basicAuth",
        "bearerToken",
        "honorLabels",
        "honorTimeStamps",
        "httpSdConfigs",
        "jobName",
        "metricsPath",
        "metricsRelabelConfigs",
        "oauth2",
        "params",
        "sampleLimit",
        "scheme",
        "scrapeInterval",
        "scrapeTimeout",
        "staticConfigs",
        "tlsConfig",
    ]

    @field_validator("scheme")
    def scheme_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(["http", "https"]):
            raise ValueError("must be one of enum values ('http', 'https')")
        return value

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )

    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of Job from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(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 basic_auth
        if self.basic_auth:
            _dict["basicAuth"] = self.basic_auth.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in http_sd_configs (list)
        _items = []
        if self.http_sd_configs:
            for _item_http_sd_configs in self.http_sd_configs:
                if _item_http_sd_configs:
                    _items.append(_item_http_sd_configs.to_dict())
            _dict["httpSdConfigs"] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in metrics_relabel_configs (list)
        _items = []
        if self.metrics_relabel_configs:
            for _item_metrics_relabel_configs in self.metrics_relabel_configs:
                if _item_metrics_relabel_configs:
                    _items.append(_item_metrics_relabel_configs.to_dict())
            _dict["metricsRelabelConfigs"] = _items
        # override the default output from pydantic by calling `to_dict()` of oauth2
        if self.oauth2:
            _dict["oauth2"] = self.oauth2.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in static_configs (list)
        _items = []
        if self.static_configs:
            for _item_static_configs in self.static_configs:
                if _item_static_configs:
                    _items.append(_item_static_configs.to_dict())
            _dict["staticConfigs"] = _items
        # override the default output from pydantic by calling `to_dict()` of tls_config
        if self.tls_config:
            _dict["tlsConfig"] = self.tls_config.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of Job from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate(
            {
                "basicAuth": BasicAuth.from_dict(obj["basicAuth"]) if obj.get("basicAuth") is not None else None,
                "bearerToken": obj.get("bearerToken"),
                "honorLabels": obj.get("honorLabels") if obj.get("honorLabels") is not None else False,
                "honorTimeStamps": obj.get("honorTimeStamps") if obj.get("honorTimeStamps") is not None else False,
                "httpSdConfigs": (
                    [HTTPServiceSD.from_dict(_item) for _item in obj["httpSdConfigs"]]
                    if obj.get("httpSdConfigs") is not None
                    else None
                ),
                "jobName": obj.get("jobName"),
                "metricsPath": obj.get("metricsPath") if obj.get("metricsPath") is not None else "/metrics",
                "metricsRelabelConfigs": (
                    [MetricsRelabelConfig.from_dict(_item) for _item in obj["metricsRelabelConfigs"]]
                    if obj.get("metricsRelabelConfigs") is not None
                    else None
                ),
                "oauth2": OAuth2.from_dict(obj["oauth2"]) if obj.get("oauth2") is not None else None,
                "params": obj.get("params"),
                "sampleLimit": obj.get("sampleLimit"),
                "scheme": obj.get("scheme") if obj.get("scheme") is not None else "http",
                "scrapeInterval": obj.get("scrapeInterval"),
                "scrapeTimeout": obj.get("scrapeTimeout"),
                "staticConfigs": (
                    [StaticConfigs.from_dict(_item) for _item in obj["staticConfigs"]]
                    if obj.get("staticConfigs") is not None
                    else None
                ),
                "tlsConfig": TLSConfig.from_dict(obj["tlsConfig"]) if obj.get("tlsConfig") is not None else None,
            }
        )
        return _obj
