# coding: utf-8

"""
    STACKIT CDN API

    API used to create and manage your CDN distributions.

    The version of the OpenAPI document: 1.0.0
    Generated by OpenAPI Generator (https://openapi-generator.tech)

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

from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from datetime import datetime
from typing import Any, ClassVar, Dict, List, Optional, Set

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

from stackit.cdn.models.config import Config
from stackit.cdn.models.distribution_waf import DistributionWaf
from stackit.cdn.models.domain import Domain
from stackit.cdn.models.status_error import StatusError


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

    config: Config
    created_at: datetime = Field(
        description="RFC3339 string defining when the distribution was created", alias="createdAt"
    )
    domains: List[Domain]
    errors: Optional[Annotated[List[StatusError], Field(min_length=1)]] = Field(
        default=None,
        description="This object may be present if, and only if the distribution has encountered an error state. ",
    )
    id: StrictStr
    project_id: StrictStr = Field(alias="projectId")
    status: StrictStr = Field(
        description="- `CREATING`: The distribution was just created.    All the relevant resources are created in the background. Once fully reconciled,   this switches to `ACTIVE`. If there are any issues, the status changes to    `ERROR`. You can look at the `errors` array to get more infos. - `ACTIVE`: The usual state. The desired configuration is synced, there are no errors - `UPDATING`: The state when there is a discrepancy between the desired and    actual configuration state. This occurs right after an update. Will switch to    `ACTIVE` or `ERROR`, depending on if synchronizing succeeds or not. - `DELETING`: The state right after a delete request was received. The distribution will stay in this status   until all resources have been successfully removed, or until we encounter an `ERROR` state.    **NOTE:** You can keep fetching the distribution while it is deleting.    After successful deletion, trying to get a distribution will return a 404 Not Found response - `ERROR`: The error state. Look at the `errors` array for more info. "
    )
    updated_at: datetime = Field(
        description="RFC3339 string which returns the last time the distribution configuration was modified. ",
        alias="updatedAt",
    )
    waf: Optional[DistributionWaf] = None
    __properties: ClassVar[List[str]] = [
        "config",
        "createdAt",
        "domains",
        "errors",
        "id",
        "projectId",
        "status",
        "updatedAt",
        "waf",
    ]

    @field_validator("created_at", mode="before")
    def created_at_change_year_zero_to_one(cls, value):
        """Workaround which prevents year 0 issue"""
        if isinstance(value, str):
            # Check for year "0000" at the beginning of the string
            # This assumes common date formats like YYYY-MM-DDTHH:MM:SS+00:00 or YYYY-MM-DDTHH:MM:SSZ
            if value.startswith("0000-01-01T") and re.match(
                r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\+\d{2}:\d{2}|Z)$", value
            ):
                # Workaround: Replace "0000" with "0001"
                return "0001" + value[4:]  # Take "0001" and append the rest of the string
        return value

    @field_validator("status")
    def status_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(["CREATING", "ACTIVE", "UPDATING", "DELETING", "ERROR"]):
            raise ValueError("must be one of enum values ('CREATING', 'ACTIVE', 'UPDATING', 'DELETING', 'ERROR')")
        return value

    @field_validator("updated_at", mode="before")
    def updated_at_change_year_zero_to_one(cls, value):
        """Workaround which prevents year 0 issue"""
        if isinstance(value, str):
            # Check for year "0000" at the beginning of the string
            # This assumes common date formats like YYYY-MM-DDTHH:MM:SS+00:00 or YYYY-MM-DDTHH:MM:SSZ
            if value.startswith("0000-01-01T") and re.match(
                r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\+\d{2}:\d{2}|Z)$", value
            ):
                # Workaround: Replace "0000" with "0001"
                return "0001" + value[4:]  # Take "0001" and append the rest of the string
        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 Distribution 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 config
        if self.config:
            _dict["config"] = self.config.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in domains (list)
        _items = []
        if self.domains:
            for _item_domains in self.domains:
                if _item_domains:
                    _items.append(_item_domains.to_dict())
            _dict["domains"] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in errors (list)
        _items = []
        if self.errors:
            for _item_errors in self.errors:
                if _item_errors:
                    _items.append(_item_errors.to_dict())
            _dict["errors"] = _items
        # override the default output from pydantic by calling `to_dict()` of waf
        if self.waf:
            _dict["waf"] = self.waf.to_dict()
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "config": Config.from_dict(obj["config"]) if obj.get("config") is not None else None,
                "createdAt": obj.get("createdAt"),
                "domains": (
                    [Domain.from_dict(_item) for _item in obj["domains"]] if obj.get("domains") is not None else None
                ),
                "errors": (
                    [StatusError.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None
                ),
                "id": obj.get("id"),
                "projectId": obj.get("projectId"),
                "status": obj.get("status"),
                "updatedAt": obj.get("updatedAt"),
                "waf": DistributionWaf.from_dict(obj["waf"]) if obj.get("waf") is not None else None,
            }
        )
        return _obj
