# coding: utf-8

"""
    Mixpeek API

    This is the Mixpeek API, providing access to various endpoints for data processing and retrieval.

    The version of the OpenAPI document: 1.3.0
    Contact: info@mixpeek.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, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from mixpeek.models.shared_clusters_triggers_models_trigger_status import SharedClustersTriggersModelsTriggerStatus
from mixpeek.models.shared_clusters_triggers_models_trigger_type import SharedClustersTriggersModelsTriggerType
from mixpeek.models.trigger_execution_config import TriggerExecutionConfig
from typing import Optional, Set
from typing_extensions import Self

class SharedClustersTriggersModelsCreateTriggerRequest(BaseModel):
    """
    Request to create a new cluster trigger.  Creates an automated trigger that executes clustering based on schedules, events, or conditions.  Requirements:     - trigger_type: REQUIRED - Determines which schedule_config fields are needed     - schedule_config: REQUIRED - Configuration specific to trigger_type     - execution_config OR cluster_id: REQUIRED - Either provide config directly or reference existing cluster  Trigger Types and schedule_config:     - **cron**: Requires {\"cron_expression\": str, \"timezone\": str}     - **interval**: Requires {\"interval_seconds\": int, \"start_immediately\": bool}     - **event**: Requires {\"event_type\": str, \"event_threshold\": int, \"collection_id\": str, \"cooldown_seconds\": int}     - **conditional**: Requires {\"condition_type\": str, \"threshold\": float, \"metric\": str, \"check_interval_seconds\": int}  Use Cases:     - Scheduled maintenance: Use cron or interval triggers     - Reactive clustering: Use event triggers to cluster when data changes     - Intelligent clustering: Use conditional triggers based on metrics  Examples:     Cron trigger (daily at 2am UTC):         {             \"trigger_type\": \"cron\",             \"schedule_config\": {                 \"cron_expression\": \"0 2 * * *\",                 \"timezone\": \"UTC\"             },             \"execution_config\": {                 \"collection_ids\": [\"col_abc123\"],                 \"config\": {                     \"algorithm\": \"kmeans\",                     \"n_clusters\": 5                 }             },             \"description\": \"Daily clustering at 2am\"         }      Interval trigger (every 6 hours):         {             \"trigger_type\": \"interval\",             \"schedule_config\": {                 \"interval_seconds\": 21600,                 \"start_immediately\": false             },             \"execution_config\": {                 \"collection_ids\": [\"col_products\"],                 \"config\": {                     \"algorithm\": \"hdbscan\",                     \"min_cluster_size\": 10                 }             },             \"description\": \"Cluster every 6 hours\"         }      Event trigger (after 100 documents added):         {             \"trigger_type\": \"event\",             \"schedule_config\": {                 \"event_type\": \"documents_added\",                 \"event_threshold\": 100,                 \"collection_id\": \"col_abc123\",                 \"cooldown_seconds\": 300             },             \"execution_config\": {                 \"collection_ids\": [\"col_abc123\"],                 \"config\": {                     \"algorithm\": \"kmeans\",                     \"n_clusters\": 3                 }             },             \"description\": \"Cluster after 100 new documents\"         }      Conditional trigger (when drift exceeds 30%):         {             \"trigger_type\": \"conditional\",             \"schedule_config\": {                 \"condition_type\": \"drift\",                 \"threshold\": 0.3,                 \"metric\": \"cosine_drift\",                 \"check_interval_seconds\": 3600             },             \"execution_config\": {                 \"collection_ids\": [\"col_abc123\"],                 \"config\": {                     \"algorithm\": \"hdbscan\",                     \"min_cluster_size\": 5                 }             },             \"description\": \"Re-cluster when drift > 30%\"         }      Using existing cluster definition:         {             \"trigger_type\": \"interval\",             \"schedule_config\": {                 \"interval_seconds\": 3600,                 \"start_immediately\": true             },             \"cluster_id\": \"cluster_xyz789\",             \"description\": \"Hourly clustering using cluster_xyz789\"         }
    """ # noqa: E501
    cluster_id: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Reference to existing cluster definition. If provided, execution_config is inherited from the cluster. Either cluster_id OR execution_config must be provided.")
    execution_config: Optional[TriggerExecutionConfig] = Field(default=None, description="OPTIONAL. Clustering configuration for this trigger. Specifies collections and algorithm to use when trigger fires. Required if cluster_id is not provided.")
    trigger_type: SharedClustersTriggersModelsTriggerType = Field(description="REQUIRED. Type of trigger to create. Determines which schedule_config fields are required. Options: 'cron', 'interval', 'event', 'conditional'.")
    schedule_config: Dict[str, Any] = Field(description="REQUIRED. Type-specific schedule configuration. Contents depend on trigger_type. See trigger type examples above for required fields.")
    description: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Human-readable description of what this trigger does. Helpful for identifying triggers in dashboards.")
    status: Optional[SharedClustersTriggersModelsTriggerStatus] = Field(default=None, description="OPTIONAL. Initial status of trigger. Defaults to 'active' (enabled). Can be set to 'paused' to create disabled trigger.")
    __properties: ClassVar[List[str]] = ["cluster_id", "execution_config", "trigger_type", "schedule_config", "description", "status"]

    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 SharedClustersTriggersModelsCreateTriggerRequest 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 execution_config
        if self.execution_config:
            _dict['execution_config'] = self.execution_config.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "cluster_id": obj.get("cluster_id"),
            "execution_config": TriggerExecutionConfig.from_dict(obj["execution_config"]) if obj.get("execution_config") is not None else None,
            "trigger_type": obj.get("trigger_type"),
            "schedule_config": obj.get("schedule_config"),
            "description": obj.get("description"),
            "status": obj.get("status")
        })
        return _obj


