# 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.logical_operator_input import LogicalOperatorInput
from mixpeek.models.sort_option import SortOption
from typing import Optional, Set
from typing_extensions import Self

class ListClusterExecutionsRequest(BaseModel):
    """
    Request parameters for listing and filtering cluster execution history.  Provides flexible querying of historical clustering executions with filtering, sorting, and search capabilities. Use to build execution history UIs, compare runs over time, and analyze clustering performance trends.  Use Cases:     - Display execution history table with sorting and filtering     - Find failed executions for debugging     - Compare metrics across successful runs     - Search executions by date range or status     - Build execution timeline visualization  Query Behavior:     - Empty request {} returns all executions sorted by created_at (newest first)     - Filters, sort, and search can be combined for complex queries     - Results are paginated (use page/page_size query params)  Note:     All fields are OPTIONAL. Omit for default behavior (all executions, newest first).
    """ # noqa: E501
    filters: Optional[LogicalOperatorInput] = Field(default=None, description="OPTIONAL. Complex filtering conditions for execution history. NOT REQUIRED - omit to return all executions. Structure: Logical operator (AND/OR) with array of conditions. Supported filter fields:   - status: Filter by execution status (pending/processing/completed/failed).   - created_at: Filter by execution start date (use gte/lte for ranges).   - num_clusters: Filter by number of clusters found.   - metrics.silhouette_score: Filter by quality threshold. Example filters:   - Status is completed: {operator: 'AND', conditions: [{field: 'status', value: 'completed', operator: '=='}]}.   - Created in last 7 days: {operator: 'AND', conditions: [{field: 'created_at', operator: 'gte', value: '2025-11-06T00:00:00Z'}]}.   - Good quality (silhouette > 0.5): {operator: 'AND', conditions: [{field: 'metrics.silhouette_score', operator: '>', value: 0.5}]}. Combine with OR: Status completed OR failed (exclude in-progress).")
    sort: Optional[SortOption] = Field(default=None, description="OPTIONAL. Sorting configuration for results. NOT REQUIRED - defaults to created_at descending (newest first). Structure: {field: 'field_name', direction: 'asc' or 'desc'}. Sortable fields:   - created_at: Sort by execution start time (default).   - completed_at: Sort by execution finish time.   - num_clusters: Sort by cluster count.   - num_points: Sort by document count.   - metrics.silhouette_score: Sort by quality score.   - status: Sort by execution status. Common use cases:   - Newest first (default): {field: 'created_at', direction: 'desc'}.   - Best quality first: {field: 'metrics.silhouette_score', direction: 'desc'}.   - Failed executions first: {field: 'status', direction: 'asc'} (alphabetical).")
    search: Optional[StrictStr] = Field(default=None, description="OPTIONAL. Full-text search query across execution metadata. NOT REQUIRED - omit for no search filtering. Searches in:   - run_id: Search by execution identifier.   - error_message: Find executions with specific error text.   - centroids.label: Search by cluster label names.   - centroids.summary: Search by cluster descriptions. Behavior:   - Case-insensitive partial matching.   - Multiple terms are AND-ed together.   - Combines with filters for complex queries. Examples:   - 'failed' → Find executions with 'failed' in error messages.   - 'product review' → Find executions with clusters about products/reviews.   - 'run_abc123' → Find specific execution by ID.")
    __properties: ClassVar[List[str]] = ["filters", "sort", "search"]

    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 ListClusterExecutionsRequest 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 filters
        if self.filters:
            _dict['filters'] = self.filters.to_dict()
        # override the default output from pydantic by calling `to_dict()` of sort
        if self.sort:
            _dict['sort'] = self.sort.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "filters": LogicalOperatorInput.from_dict(obj["filters"]) if obj.get("filters") is not None else None,
            "sort": SortOption.from_dict(obj["sort"]) if obj.get("sort") is not None else None,
            "search": obj.get("search")
        })
        return _obj


