# 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, StrictInt
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 ClusterExecutionListStats(BaseModel):
    """
    Aggregate statistics calculated across all executions in the current result set.  Provides summary metrics for the filtered/searched execution history, useful for dashboards, monitoring, and trend analysis. Statistics are calculated only for the executions returned in the current query (respects filters and pagination).  Use Cases:     - Display execution summary cards (\"5 completed, 2 failed, 3 pending\")     - Show average execution time trend     - Monitor clustering performance over time     - Build execution health dashboard     - Compare stats across different time periods (via filters)  Important:     Stats reflect only the current result set, not all historical executions.     Apply filters to calculate stats for specific time ranges or statuses.
    """ # noqa: E501
    total_executions: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=0, description="OPTIONAL (always provided). Total number of executions in current result set. Equals length of results array. Use for:   - Display total count in UI ('Showing 10 of 100 executions').   - Validate pagination (total should match page_size × pages).   - Check if filters returned any results (0 = no matches). Note: This is the count in the current page, not all executions.")
    executions_by_status: Optional[Dict[str, StrictInt]] = Field(default=None, description="OPTIONAL (always provided). Count of executions grouped by status. Keys: 'pending', 'processing', 'completed', 'failed'. Values: Number of executions in each status. Use for:   - Status distribution chart (pie/bar chart).   - Health monitoring (high failed count = problem).   - Progress tracking (pending + processing = in-flight jobs). Example: {'completed': 45, 'failed': 3, 'processing': 2, 'pending': 0}. Empty dict {} if no executions in result set.")
    avg_execution_time_ms: Optional[Union[Annotated[float, Field(strict=True, ge=0.0)], Annotated[int, Field(strict=True, ge=0)]]] = Field(default=0.0, description="OPTIONAL (always provided). Average execution duration in milliseconds. Calculated as: mean(completed_at - created_at) for completed/failed executions. Excludes pending/processing executions (no completed_at yet). Use for:   - Performance monitoring ('Average: 5.2 seconds').   - Trend analysis (is clustering getting slower over time?).   - Capacity planning (estimate time for future runs). 0.0 if: No completed/failed executions in result set. Typical values:   - Small datasets (< 100 docs): 1000-5000ms (1-5 seconds).   - Medium datasets (100-1000 docs): 5000-30000ms (5-30 seconds).   - Large datasets (1000+ docs): 30000-300000ms (30 seconds - 5 minutes).")
    total_documents_clustered: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=0, description="OPTIONAL (always provided). Total documents processed across all executions. Calculated as: sum(num_points) for all executions in result set. Use for:   - Volume tracking ('Processed 10,000 documents').   - Cost estimation (larger datasets = more compute).   - Data growth monitoring (compare over time). 0 if: No executions in result set. Note: Same document may be counted multiple times if re-clustered.")
    avg_num_clusters: Optional[Union[Annotated[float, Field(strict=True, ge=0.0)], Annotated[int, Field(strict=True, ge=0)]]] = Field(default=0.0, description="OPTIONAL (always provided). Average number of clusters found per execution. Calculated as: mean(num_clusters) for all executions in result set. Use for:   - Clustering consistency check (stable avg = consistent results).   - Algorithm tuning (avg too high/low may need parameter adjustment).   - Trend analysis (is clustering finding more/fewer clusters over time?). 0.0 if: No executions in result set. Typical values:   - Under-clustering: < 3 clusters (data may be too diverse).   - Good clustering: 3-20 clusters (manageable, meaningful groups).   - Over-clustering: > 20 clusters (too granular, hard to interpret).")
    __properties: ClassVar[List[str]] = ["total_executions", "executions_by_status", "avg_execution_time_ms", "total_documents_clustered", "avg_num_clusters"]

    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 ClusterExecutionListStats 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,
        )
        return _dict

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

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

        _obj = cls.model_validate({
            "total_executions": obj.get("total_executions") if obj.get("total_executions") is not None else 0,
            "executions_by_status": obj.get("executions_by_status"),
            "avg_execution_time_ms": obj.get("avg_execution_time_ms") if obj.get("avg_execution_time_ms") is not None else 0.0,
            "total_documents_clustered": obj.get("total_documents_clustered") if obj.get("total_documents_clustered") is not None else 0,
            "avg_num_clusters": obj.get("avg_num_clusters") if obj.get("avg_num_clusters") is not None else 0.0
        })
        return _obj


