# 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
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.cdn.models.match_condition import MatchCondition
from stackit.cdn.models.matcher import Matcher


class RedirectRule(BaseModel):
    """
    A single redirect rule defining a source pattern and a target URL.
    """  # noqa: E501

    description: Optional[StrictStr] = Field(default=None, description="An optional description for the redirect rule.")
    enabled: Optional[StrictBool] = Field(default=True, description="A toggle to enable or disable the redirect rule.")
    matchers: Annotated[List[Matcher], Field(min_length=1)] = Field(
        description="A list of matchers that define when this rule should apply. At least one matcher is required."
    )
    rule_match_condition: Optional[MatchCondition] = Field(default=MatchCondition.ANY, alias="ruleMatchCondition")
    status_code: Annotated[int, Field(le=399, strict=True, ge=300)] = Field(
        description="The HTTP status code for the redirect. Must be one of 301, 302, 303, 307, or 308.",
        alias="statusCode",
    )
    target_url: StrictStr = Field(description="The target URL to redirect to. Must be a valid URI.", alias="targetUrl")
    __properties: ClassVar[List[str]] = [
        "description",
        "enabled",
        "matchers",
        "ruleMatchCondition",
        "statusCode",
        "targetUrl",
    ]

    @field_validator("status_code")
    def status_code_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set([301, 302, 303, 307, 308]):
            raise ValueError("must be one of enum values (301, 302, 303, 307, 308)")
        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 RedirectRule 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 each item in matchers (list)
        _items = []
        if self.matchers:
            for _item_matchers in self.matchers:
                if _item_matchers:
                    _items.append(_item_matchers.to_dict())
            _dict["matchers"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "description": obj.get("description"),
                "enabled": obj.get("enabled") if obj.get("enabled") is not None else True,
                "matchers": (
                    [Matcher.from_dict(_item) for _item in obj["matchers"]] if obj.get("matchers") is not None else None
                ),
                "ruleMatchCondition": (
                    obj.get("ruleMatchCondition") if obj.get("ruleMatchCondition") is not None else MatchCondition.ANY
                ),
                "statusCode": obj.get("statusCode"),
                "targetUrl": obj.get("targetUrl"),
            }
        )
        return _obj
