# coding: utf-8

"""
    Pinterest REST API

    Pinterest's REST API

    The version of the OpenAPI document: 5.23.0
    Contact: blah+oapicf@cliffano.com
    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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from pinterestsdk.models.audience_category import AudienceCategory
from pinterestsdk.models.audience_demographics import AudienceDemographics
from pinterestsdk.models.audience_insight_type import AudienceInsightType
from typing import Optional, Set
from typing_extensions import Self

class AudienceInsightsResponse(BaseModel):
    """
    Audience interests and demographics.
    """ # noqa: E501
    categories: Optional[List[AudienceCategory]] = Field(default=None, description="Category interest distribution")
    var_date: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="Generation date", alias="date")
    demographics: Optional[AudienceDemographics] = None
    size: Optional[StrictInt] = Field(default=None, description="Population count.")
    size_is_upper_bound: Optional[StrictBool] = Field(default=None, description="Indicates whether the audience size has been rounded up to the next highest upper boundary.")
    type: Optional[AudienceInsightType] = AudienceInsightType.YOUR_TOTAL_AUDIENCE
    __properties: ClassVar[List[str]] = ["categories", "date", "demographics", "size", "size_is_upper_bound", "type"]

    @field_validator('var_date')
    def var_date_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if value is None:
            return value

        if not re.match(r"^\d{4}-\d{2}-\d{2}$", value):
            raise ValueError(r"must validate the regular expression /^\d{4}-\d{2}-\d{2}$/")
        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 AudienceInsightsResponse 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 categories (list)
        _items = []
        if self.categories:
            for _item_categories in self.categories:
                if _item_categories:
                    _items.append(_item_categories.to_dict())
            _dict['categories'] = _items
        # override the default output from pydantic by calling `to_dict()` of demographics
        if self.demographics:
            _dict['demographics'] = self.demographics.to_dict()
        # set to None if var_date (nullable) is None
        # and model_fields_set contains the field
        if self.var_date is None and "var_date" in self.model_fields_set:
            _dict['date'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "categories": [AudienceCategory.from_dict(_item) for _item in obj["categories"]] if obj.get("categories") is not None else None,
            "date": obj.get("date"),
            "demographics": AudienceDemographics.from_dict(obj["demographics"]) if obj.get("demographics") is not None else None,
            "size": obj.get("size"),
            "size_is_upper_bound": obj.get("size_is_upper_bound"),
            "type": obj.get("type") if obj.get("type") is not None else AudienceInsightType.YOUR_TOTAL_AUDIENCE
        })
        return _obj


