# 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, StrictFloat, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self

class ConversionMSOTEvents(BaseModel):
    """
    Object containing the MSOT conversion events.
    """ # noqa: E501
    action_timestamps: Optional[List[StrictInt]] = Field(default=None, description="Timestamp(s) when the ad action(s) happened. Unix timestamp in seconds.")
    ad_group_id: Annotated[str, Field(strict=True)] = Field(description="The ID of the ad group that was attributed to the conversion event.")
    attribution_model: Optional[StrictStr] = Field(default=None, description="The attribution model used to attribute the conversion event.")
    attribution_scope: StrictStr = Field(description="Ad event type.")
    attribution_score: Optional[Union[Annotated[float, Field(le=1, strict=True, gt=0)], Annotated[int, Field(le=1, strict=True, gt=0)]]] = Field(default=None, description="Credit given to the attributed ad actions. Allowed values are > 0 and <= 1.")
    campaign_id: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="The ID of the campaign that was attributed to the conversion event.")
    currency: Optional[Any] = None
    event_id: Annotated[str, Field(strict=True, max_length=256)] = Field(description="A unique id string that identifies this event. If you are already sending us events through Conversions API, then this id should match the event_id sent through Conversions API.")
    event_name: StrictStr = Field(description="Type of user event.")
    event_timestamp: StrictInt = Field(description="The time when the event occurred. Unix timestamp in seconds.")
    total_event_touchpoints: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=None, description="Total number of ad events including other non-Pinterest ad platforms.")
    total_events: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=None, description="Total number of conversion events that are reported in one API call. <p>If you are sending one API request for one attributed conversion event then this value should be 1.</p> <p>If you are sending multiple attributed conversion events in one API request then this value should be the total number of attributed conversion events in the request.</p>")
    value: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Order value of the conversion event. Required if <code>event_name</code> is 'add_to_cart' or 'checkout'.")
    __properties: ClassVar[List[str]] = ["action_timestamps", "ad_group_id", "attribution_model", "attribution_scope", "attribution_score", "campaign_id", "currency", "event_id", "event_name", "event_timestamp", "total_event_touchpoints", "total_events", "value"]

    @field_validator('ad_group_id')
    def ad_group_id_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if not re.match(r"^\d+$", value):
            raise ValueError(r"must validate the regular expression /^\d+$/")
        return value

    @field_validator('attribution_model')
    def attribution_model_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

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

    @field_validator('attribution_scope')
    def attribution_scope_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['view', 'engagement', 'click']):
            raise ValueError("must be one of enum values ('view', 'engagement', 'click')")
        return value

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

        if not re.match(r"^\d+$", value):
            raise ValueError(r"must validate the regular expression /^\d+$/")
        return value

    @field_validator('event_name')
    def event_name_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['add_to_cart', 'checkout', 'lead', 'signup']):
            raise ValueError("must be one of enum values ('add_to_cart', 'checkout', 'lead', 'signup')")
        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 ConversionMSOTEvents 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 currency
        if self.currency:
            _dict['currency'] = self.currency.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "action_timestamps": obj.get("action_timestamps"),
            "ad_group_id": obj.get("ad_group_id"),
            "attribution_model": obj.get("attribution_model"),
            "attribution_scope": obj.get("attribution_scope"),
            "attribution_score": obj.get("attribution_score"),
            "campaign_id": obj.get("campaign_id"),
            "currency": Currency.from_dict(obj["currency"]) if obj.get("currency") is not None else None,
            "event_id": obj.get("event_id"),
            "event_name": obj.get("event_name"),
            "event_timestamp": obj.get("event_timestamp"),
            "total_event_touchpoints": obj.get("total_event_touchpoints"),
            "total_events": obj.get("total_events"),
            "value": obj.get("value")
        })
        return _obj


