# 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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from mixpeek.models.attribute_based_config import AttributeBasedConfig
from mixpeek.models.cluster_stats import ClusterStats
from mixpeek.models.cluster_type import ClusterType
from mixpeek.models.llm_labeling_output import LLMLabelingOutput
from mixpeek.models.logical_operator_output import LogicalOperatorOutput
from mixpeek.models.source_enrichment_config import SourceEnrichmentConfig
from mixpeek.models.task_status_enum import TaskStatusEnum
from mixpeek.models.vector_based_config_output import VectorBasedConfigOutput
from typing import Optional, Set
from typing_extensions import Self

class ClusterModel(BaseModel):
    """
    Cluster metadata stored in MongoDB.
    """ # noqa: E501
    collection_ids: Optional[Annotated[List[StrictStr], Field(min_length=1)]] = Field(default=None, description="Collections to cluster together")
    cluster_name: Optional[StrictStr] = Field(default=None, description="Optional human-friendly name for the clustering job")
    cluster_type: Optional[ClusterType] = Field(default=None, description="Vector or attribute clustering")
    vector_config: Optional[VectorBasedConfigOutput] = Field(default=None, description="Required when cluster_type is 'vector'")
    attribute_config: Optional[AttributeBasedConfig] = Field(default=None, description="Required when cluster_type is 'attribute'")
    filters: Optional[LogicalOperatorOutput] = Field(default=None, description="Optional filters to pre-filter documents before clustering (same format as list documents). Applied during Qdrant scroll before parquet export. Useful for clustering subsets like: status='active', category='electronics', etc.")
    llm_labeling: Optional[LLMLabelingOutput] = Field(default=None, description="Optional configuration for LLM-based cluster labeling. When provided with enabled=True, clusters will have semantic labels generated by LLM instead of generic labels like 'Cluster 0'. When not provided or enabled=False, uses fallback labels.")
    enrich_source_collection: Optional[StrictBool] = Field(default=False, description="If True, cluster results are written back to source collection(s) in-place instead of creating new output collections. Documents will be enriched with cluster_id, cluster_label, distance_to_centroid, and optionally other metadata. Similar to taxonomy enrichment pattern.")
    source_enrichment_config: Optional[SourceEnrichmentConfig] = Field(default=None, description="Configuration for source collection enrichment (only used if enrich_source_collection=True). Controls which fields are added to source documents and field naming conventions.")
    cluster_id: Optional[StrictStr] = Field(default=None, description="Unique cluster identifier")
    parquet_path: Optional[StrictStr] = Field(default=None, description="S3 path to parquet files with cluster data")
    members_key: Optional[StrictStr] = Field(default=None, description="S3 key to members.parquet (if saved)")
    num_clusters: Optional[StrictInt] = Field(default=None, description="Number of clusters found")
    cluster_stats: Optional[ClusterStats] = Field(default=None, description="Clustering quality metrics")
    status: Optional[TaskStatusEnum] = Field(default=None, description="Clustering job status")
    task_id: Optional[StrictStr] = Field(default=None, description="Associated task ID for clustering job")
    last_run_id: Optional[StrictStr] = Field(default=None, description="Run ID of the most recent successful clustering execution. Used to retrieve execution results.")
    created_at: Optional[datetime] = Field(default=None, description="When the cluster was created")
    updated_at: Optional[datetime] = Field(default=None, description="When the cluster was last updated")
    metadata: Optional[Dict[str, Any]] = Field(default=None, description="Additional user-defined metadata for the cluster")
    __properties: ClassVar[List[str]] = ["collection_ids", "cluster_name", "cluster_type", "vector_config", "attribute_config", "filters", "llm_labeling", "enrich_source_collection", "source_enrichment_config", "cluster_id", "parquet_path", "members_key", "num_clusters", "cluster_stats", "status", "task_id", "last_run_id", "created_at", "updated_at", "metadata"]

    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 ClusterModel 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 vector_config
        if self.vector_config:
            _dict['vector_config'] = self.vector_config.to_dict()
        # override the default output from pydantic by calling `to_dict()` of attribute_config
        if self.attribute_config:
            _dict['attribute_config'] = self.attribute_config.to_dict()
        # 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 llm_labeling
        if self.llm_labeling:
            _dict['llm_labeling'] = self.llm_labeling.to_dict()
        # override the default output from pydantic by calling `to_dict()` of source_enrichment_config
        if self.source_enrichment_config:
            _dict['source_enrichment_config'] = self.source_enrichment_config.to_dict()
        # override the default output from pydantic by calling `to_dict()` of cluster_stats
        if self.cluster_stats:
            _dict['cluster_stats'] = self.cluster_stats.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "collection_ids": obj.get("collection_ids"),
            "cluster_name": obj.get("cluster_name"),
            "cluster_type": obj.get("cluster_type"),
            "vector_config": VectorBasedConfigOutput.from_dict(obj["vector_config"]) if obj.get("vector_config") is not None else None,
            "attribute_config": AttributeBasedConfig.from_dict(obj["attribute_config"]) if obj.get("attribute_config") is not None else None,
            "filters": LogicalOperatorOutput.from_dict(obj["filters"]) if obj.get("filters") is not None else None,
            "llm_labeling": LLMLabelingOutput.from_dict(obj["llm_labeling"]) if obj.get("llm_labeling") is not None else None,
            "enrich_source_collection": obj.get("enrich_source_collection") if obj.get("enrich_source_collection") is not None else False,
            "source_enrichment_config": SourceEnrichmentConfig.from_dict(obj["source_enrichment_config"]) if obj.get("source_enrichment_config") is not None else None,
            "cluster_id": obj.get("cluster_id"),
            "parquet_path": obj.get("parquet_path"),
            "members_key": obj.get("members_key"),
            "num_clusters": obj.get("num_clusters"),
            "cluster_stats": ClusterStats.from_dict(obj["cluster_stats"]) if obj.get("cluster_stats") is not None else None,
            "status": obj.get("status"),
            "task_id": obj.get("task_id"),
            "last_run_id": obj.get("last_run_id"),
            "created_at": obj.get("created_at"),
            "updated_at": obj.get("updated_at"),
            "metadata": obj.get("metadata")
        })
        return _obj


