# 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
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.cluster_execution_list_stats import ClusterExecutionListStats
from mixpeek.models.cluster_execution_result import ClusterExecutionResult
from mixpeek.models.pagination_response import PaginationResponse
from typing import Optional, Set
from typing_extensions import Self

class ListClusterExecutionsResponse(BaseModel):
    """
    Complete response for cluster execution history listing endpoint.  Returns paginated execution history with filtering, sorting, and aggregate statistics. Use to build execution history UIs, monitoring dashboards, and performance analytics.  Response Structure:     - results: Array of execution details (paginated)     - pagination: Page navigation info (current page, total pages, etc.)     - total_count: Total matching executions (across all pages)     - stats: Aggregated metrics for current result set  Use Cases:     - Build execution history table with pagination     - Display execution status dashboard with charts     - Monitor clustering performance trends     - Debug failed executions     - Compare quality metrics across runs  Pagination Behavior:     - Default: 10 executions per page     - Use query params: ?page=1&page_size=20     - results contains current page only     - total_count shows all matching executions     - pagination provides navigation links  Example Workflow:     1. Request: POST /clusters/{id}/executions/list with filters     2. Response: 50 total executions, showing page 1 (10 results)     3. Display: Show 10 results + \"Page 1 of 5\" + aggregate stats     4. Navigate: Use pagination.next_page for next 10 results
    """ # noqa: E501
    results: List[ClusterExecutionResult] = Field(description="REQUIRED. Array of cluster execution results for the current page. Length: 0 to page_size (default 10, max typically 100). Empty array [] if:   - No executions exist for this cluster.   - Filters matched no results.   - Requested page beyond available pages. Sorted by: created_at descending (newest first) by default. Override with sort parameter in request. Each item contains:   - run_id: Unique execution identifier.   - status: pending/processing/completed/failed.   - num_clusters: Clusters found.   - metrics: Quality scores (if available).   - centroids: Cluster labels and summaries (if available).   - created_at/completed_at: Timestamps.   - error_message: Error details (if failed). Use for: Rendering execution history table rows.")
    pagination: PaginationResponse = Field(description="REQUIRED. Pagination metadata for navigating result pages. Contains:   - total: Total items across all pages (same as total_count).   - page: Current page number (1-indexed).   - page_size: Items per page.   - total_pages: Total number of pages.   - next_page: URL for next page (null if last page).   - previous_page: URL for previous page (null if first page). Use for:   - Pagination controls ('Page 2 of 5').   - Next/Previous buttons (check null for disabled state).   - Showing X-Y of Z results calculations.")
    total_count: Annotated[int, Field(strict=True, ge=0)] = Field(description="REQUIRED. Total number of executions matching the query across ALL pages. Use for:   - Display total count ('Found 127 executions').   - Calculate pagination ('Showing 1-10 of 127').   - Validate filters (0 = no matches, refine query). Behavior:   - Includes all filtered results, not just current page.   - Changes when filters are applied.   - Equals len(results) only if all results fit on one page. Example:   - Query returns 127 executions total.   - Page size = 10.   - Current page (1) shows results[0:10].   - total_count = 127 (not 10).")
    stats: Optional[ClusterExecutionListStats] = Field(default=None, description="OPTIONAL. Aggregate statistics for executions in current result set. NOT REQUIRED - may be null if stats calculation disabled. Typically always provided for execution listing. Contains:   - total_executions: Count in current page.   - executions_by_status: Status distribution {'completed': 45, 'failed': 3}.   - avg_execution_time_ms: Mean duration.   - total_documents_clustered: Sum of all processed documents.   - avg_num_clusters: Mean clusters per execution. Use for:   - Summary cards above table.   - Status pie chart.   - Performance metrics dashboard. Note:   - Stats calculated for current page only (or all if no pagination).   - Respects filters (stats for filtered subset).")
    __properties: ClassVar[List[str]] = ["results", "pagination", "total_count", "stats"]

    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 ListClusterExecutionsResponse 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 results (list)
        _items = []
        if self.results:
            for _item_results in self.results:
                if _item_results:
                    _items.append(_item_results.to_dict())
            _dict['results'] = _items
        # override the default output from pydantic by calling `to_dict()` of pagination
        if self.pagination:
            _dict['pagination'] = self.pagination.to_dict()
        # override the default output from pydantic by calling `to_dict()` of stats
        if self.stats:
            _dict['stats'] = self.stats.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "results": [ClusterExecutionResult.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None,
            "pagination": PaginationResponse.from_dict(obj["pagination"]) if obj.get("pagination") is not None else None,
            "total_count": obj.get("total_count"),
            "stats": ClusterExecutionListStats.from_dict(obj["stats"]) if obj.get("stats") is not None else None
        })
        return _obj


