# coding: utf-8

"""
    Rapidata Asset API

    The API for the Rapidata Asset service

    The version of the OpenAPI document: v1
    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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from rapidata.api_client.models.audience_boost_model import AudienceBoostModel
from rapidata.api_client.models.feature_flag import FeatureFlag
from rapidata.api_client.models.flow_type import FlowType
from rapidata.api_client.models.pid_batch_mode import PidBatchMode
from typing import Optional, Set
from typing_extensions import Self

class IFlowModelRankingFlowModel(BaseModel):
    """
    IFlowModelRankingFlowModel
    """ # noqa: E501
    t: StrictStr = Field(alias="_t")
    id: StrictStr = Field(description="The unique identifier of the flow.")
    type: FlowType
    name: StrictStr = Field(description="The name of the flow.")
    flow_item_count: StrictInt = Field(description="The total number of items that have been added to this flow. Incremented atomically on each item creation.", alias="flowItemCount")
    target_response_count: StrictInt = Field(description="Target average response count per completed item. Enables PID-based automatic rate control when set. Null disables PID.", alias="targetResponseCount")
    pid_proportional_gain: Union[StrictFloat, StrictInt] = Field(description="PID proportional gain. Controls how strongly the rate reacts to the current error between target and actual response counts.", alias="pidProportionalGain")
    pid_integral_gain: Union[StrictFloat, StrictInt] = Field(description="PID integral gain. Eliminates steady-state error by accumulating error over time. Includes anti-windup clamping.", alias="pidIntegralGain")
    pid_derivative_gain: Union[StrictFloat, StrictInt] = Field(description="PID derivative gain. Provides damping by reacting to the rate of change of the error, helping prevent overshoot.", alias="pidDerivativeGain")
    pid_min_sessions_per_minute: StrictInt = Field(description="Minimum sessions per minute the PID controller can set. Prevents the rate from dropping to zero.", alias="pidMinSessionsPerMinute")
    pid_max_sessions_per_minute: StrictInt = Field(description="Maximum sessions per minute the PID controller can set. Prevents the rate from exceeding infrastructure capacity.", alias="pidMaxSessionsPerMinute")
    pid_batch_mode: PidBatchMode = Field(alias="pidBatchMode")
    serve_timeout_seconds: StrictInt = Field(description="Maximum time in seconds a user has to submit an answer after loading the task. Null uses the system-wide default.", alias="serveTimeoutSeconds")
    drain_duration_seconds: StrictInt = Field(description="Grace period in seconds after an item stops receiving new serves, allowing in-flight responses to complete.", alias="drainDurationSeconds")
    serve_to_response_ratio: Union[StrictFloat, StrictInt] = Field(description="Ratio of serves to responses used to calculate how many tasks to serve per expected response.", alias="serveToResponseRatio")
    global_boost_level: StrictInt = Field(description="Priority multiplier for the flow's campaign. Higher values increase annotator compensation to attract more responses.", alias="globalBoostLevel")
    audience_boosts: List[AudienceBoostModel] = Field(alias="audienceBoosts")
    criteria: Optional[StrictStr] = Field(description="The comparison instruction shown to annotators during ranking tasks (e.g. \"Which image is sharper?\").")
    starting_elo: StrictInt = Field(description="The initial Elo rating assigned to new items entering the ranking. Standard default is 1200.", alias="startingElo")
    k_factor: StrictInt = Field(description="Elo K-factor controlling rating volatility. Higher values cause larger rating changes per comparison. Used as a direct multiplier on the Elo change formula.", alias="kFactor")
    scaling_factor: StrictInt = Field(description="Elo scaling factor that determines how rating differences translate to expected win probabilities. A difference equal to the scaling factor gives the higher-rated item approximately 90% expected win rate.", alias="scalingFactor")
    min_responses: StrictInt = Field(description="Minimum number of responses a ranking item must receive before it is considered sufficiently evaluated.", alias="minResponses")
    max_responses: StrictInt = Field(description="Maximum number of responses a ranking item can receive before being removed from active ranking. Null allows unlimited responses.", alias="maxResponses")
    feature_flags: List[FeatureFlag] = Field(alias="featureFlags")
    owner_id: StrictStr = Field(description="The ID of the customer who owns the flow.", alias="ownerId")
    owner_mail: StrictStr = Field(description="The email of the customer who owns the flow.", alias="ownerMail")
    created_at: datetime = Field(description="The timestamp when the flow was created.", alias="createdAt")
    __properties: ClassVar[List[str]] = ["_t", "id", "type", "name", "flowItemCount", "targetResponseCount", "pidProportionalGain", "pidIntegralGain", "pidDerivativeGain", "pidMinSessionsPerMinute", "pidMaxSessionsPerMinute", "pidBatchMode", "serveTimeoutSeconds", "drainDurationSeconds", "serveToResponseRatio", "globalBoostLevel", "audienceBoosts", "criteria", "startingElo", "kFactor", "scalingFactor", "minResponses", "maxResponses", "featureFlags", "ownerId", "ownerMail", "createdAt"]

    @field_validator('t')
    def t_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['RankingFlow']):
            raise ValueError("must be one of enum values ('RankingFlow')")
        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 IFlowModelRankingFlowModel 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 audience_boosts (list)
        _items = []
        if self.audience_boosts:
            for _item_audience_boosts in self.audience_boosts:
                if _item_audience_boosts:
                    _items.append(_item_audience_boosts.to_dict())
            _dict['audienceBoosts'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in feature_flags (list)
        _items = []
        if self.feature_flags:
            for _item_feature_flags in self.feature_flags:
                if _item_feature_flags:
                    _items.append(_item_feature_flags.to_dict())
            _dict['featureFlags'] = _items
        # set to None if criteria (nullable) is None
        # and model_fields_set contains the field
        if self.criteria is None and "criteria" in self.model_fields_set:
            _dict['criteria'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "_t": obj.get("_t"),
            "id": obj.get("id"),
            "type": obj.get("type"),
            "name": obj.get("name"),
            "flowItemCount": obj.get("flowItemCount"),
            "targetResponseCount": obj.get("targetResponseCount"),
            "pidProportionalGain": obj.get("pidProportionalGain"),
            "pidIntegralGain": obj.get("pidIntegralGain"),
            "pidDerivativeGain": obj.get("pidDerivativeGain"),
            "pidMinSessionsPerMinute": obj.get("pidMinSessionsPerMinute"),
            "pidMaxSessionsPerMinute": obj.get("pidMaxSessionsPerMinute"),
            "pidBatchMode": obj.get("pidBatchMode"),
            "serveTimeoutSeconds": obj.get("serveTimeoutSeconds"),
            "drainDurationSeconds": obj.get("drainDurationSeconds"),
            "serveToResponseRatio": obj.get("serveToResponseRatio"),
            "globalBoostLevel": obj.get("globalBoostLevel"),
            "audienceBoosts": [AudienceBoostModel.from_dict(_item) for _item in obj["audienceBoosts"]] if obj.get("audienceBoosts") is not None else None,
            "criteria": obj.get("criteria"),
            "startingElo": obj.get("startingElo"),
            "kFactor": obj.get("kFactor"),
            "scalingFactor": obj.get("scalingFactor"),
            "minResponses": obj.get("minResponses"),
            "maxResponses": obj.get("maxResponses"),
            "featureFlags": [FeatureFlag.from_dict(_item) for _item in obj["featureFlags"]] if obj.get("featureFlags") is not None else None,
            "ownerId": obj.get("ownerId"),
            "ownerMail": obj.get("ownerMail"),
            "createdAt": obj.get("createdAt")
        })
        return _obj


