# 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, StrictBool, StrictFloat, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from mixpeek.models.algorithm_params import AlgorithmParams
from mixpeek.models.clustering_algorithm import ClusteringAlgorithm
from mixpeek.models.dbscan_parameters import DbscanParameters
from mixpeek.models.hdbscan_parameters import HdbscanParameters
from mixpeek.models.kmeans_parameters import KmeansParameters
from mixpeek.models.weight_learning_config import WeightLearningConfig
from typing import Optional, Set
from typing_extensions import Self

class VectorBasedConfigOutput(BaseModel):
    """
    Configuration for vector-based clustering.  Use canonical feature URIs to specify which vector embeddings to cluster. Feature URIs follow the format: mixpeek://{extractor}@{version}/{output}  Supports both single and multi-feature clustering: - Single feature: Provide one feature_uri for standard clustering - Multi-feature: Provide multiple feature_uris for hybrid clustering  Examples:     Single feature:     {         \"feature_uri\": \"mixpeek://multimodal_extractor@v1/vertex_multimodal_embedding\",         \"clustering_method\": \"hdbscan\",         \"sample_size\": 1000     }      Multi-feature:     {         \"feature_uris\": [             \"mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1\",             \"mixpeek://image_extractor@v1/embedding\"         ],         \"clustering_method\": \"hdbscan\",         \"multi_feature_strategy\": \"concatenate\"     }
    """ # noqa: E501
    feature_uri: Optional[StrictStr] = Field(default=None, description="DEPRECATED: Use feature_uris instead. Canonical feature URI for the vector embedding to cluster. Format: 'mixpeek://{extractor}@{version}/{output}'. For multi-feature clustering, use feature_uris (plural) instead.")
    feature_uris: Optional[Annotated[List[StrictStr], Field(min_length=1)]] = Field(default=None, description="RECOMMENDED. List of feature URIs to cluster. Format: 'mixpeek://{extractor}@{version}/{output}'. For single-feature clustering, provide a list with one element. For multi-feature clustering, provide multiple feature URIs. Each feature must exist in all input collections.")
    clustering_method: ClusteringAlgorithm = Field(description="Clustering algorithm to use")
    sample_size: Optional[StrictInt] = Field(default=None, description="Number of samples to use for clustering")
    kmeans_parameters: Optional[KmeansParameters] = None
    dbscan_parameters: Optional[DbscanParameters] = None
    hdbscan_parameters: Optional[HdbscanParameters] = None
    algorithm_params: Optional[AlgorithmParams] = None
    multi_feature_strategy: Optional[StrictStr] = Field(default='concatenate', description="Strategy for handling multiple feature vectors: - concatenate: Combine embeddings into one vector, single clustering - independent: Run separate clustering per feature - weighted: Learn optimal feature weights")
    normalize_features: Optional[StrictBool] = Field(default=True, description="Apply L2 normalization to each feature block before concatenation. Prevents feature dominance when combining different modalities. Only applies when multi_feature_strategy='concatenate'.")
    feature_weights: Optional[Dict[str, Union[StrictFloat, StrictInt]]] = Field(default=None, description="Optional per-feature weights (0.0-1.0) for concatenation strategy. Keys are feature URIs, values are weights. Example: {'mixpeek://text@v1/emb': 0.7, 'mixpeek://image@v1/emb': 0.3}. Defaults to equal weights (1.0) if not specified. Only applies when multi_feature_strategy='concatenate'. If multi_feature_strategy='weighted' and this is None, weights are learned automatically using weight_learning_config.")
    weight_learning_config: Optional[WeightLearningConfig] = Field(default=None, description="Configuration for automatic feature weight learning. Only used when multi_feature_strategy='weighted' and feature_weights is None. If feature_weights is provided, manual weights are used instead of learning. If this is None when learning is needed, default WeightLearningConfig is used.")
    output_strategy: Optional[StrictStr] = Field(default='single', description="Output collection creation strategy: - single: Create one collection with all feature vectors - per_feature: Create separate collections for each feature (for hierarchical taxonomies)")
    effective_feature_method: Optional[StrictStr] = Field(default='mean', description="Method for calculating cluster centroids: - mean: Average of all vectors in cluster - median: Median vector (robust to outliers) - medoid: Actual cluster member closest to centroid")
    enrich_source: Optional[StrictBool] = Field(default=False, description="Whether to enrich source documents with cluster_id")
    __properties: ClassVar[List[str]] = ["feature_uri", "feature_uris", "clustering_method", "sample_size", "kmeans_parameters", "dbscan_parameters", "hdbscan_parameters", "algorithm_params", "multi_feature_strategy", "normalize_features", "feature_weights", "weight_learning_config", "output_strategy", "effective_feature_method", "enrich_source"]

    @field_validator('multi_feature_strategy')
    def multi_feature_strategy_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['concatenate', 'independent', 'weighted']):
            raise ValueError("must be one of enum values ('concatenate', 'independent', 'weighted')")
        return value

    @field_validator('output_strategy')
    def output_strategy_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['single', 'per_feature']):
            raise ValueError("must be one of enum values ('single', 'per_feature')")
        return value

    @field_validator('effective_feature_method')
    def effective_feature_method_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['mean', 'median', 'medoid']):
            raise ValueError("must be one of enum values ('mean', 'median', 'medoid')")
        return value

    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 VectorBasedConfigOutput 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 kmeans_parameters
        if self.kmeans_parameters:
            _dict['kmeans_parameters'] = self.kmeans_parameters.to_dict()
        # override the default output from pydantic by calling `to_dict()` of dbscan_parameters
        if self.dbscan_parameters:
            _dict['dbscan_parameters'] = self.dbscan_parameters.to_dict()
        # override the default output from pydantic by calling `to_dict()` of hdbscan_parameters
        if self.hdbscan_parameters:
            _dict['hdbscan_parameters'] = self.hdbscan_parameters.to_dict()
        # override the default output from pydantic by calling `to_dict()` of algorithm_params
        if self.algorithm_params:
            _dict['algorithm_params'] = self.algorithm_params.to_dict()
        # override the default output from pydantic by calling `to_dict()` of weight_learning_config
        if self.weight_learning_config:
            _dict['weight_learning_config'] = self.weight_learning_config.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "feature_uri": obj.get("feature_uri"),
            "feature_uris": obj.get("feature_uris"),
            "clustering_method": obj.get("clustering_method"),
            "sample_size": obj.get("sample_size"),
            "kmeans_parameters": KmeansParameters.from_dict(obj["kmeans_parameters"]) if obj.get("kmeans_parameters") is not None else None,
            "dbscan_parameters": DbscanParameters.from_dict(obj["dbscan_parameters"]) if obj.get("dbscan_parameters") is not None else None,
            "hdbscan_parameters": HdbscanParameters.from_dict(obj["hdbscan_parameters"]) if obj.get("hdbscan_parameters") is not None else None,
            "algorithm_params": AlgorithmParams.from_dict(obj["algorithm_params"]) if obj.get("algorithm_params") is not None else None,
            "multi_feature_strategy": obj.get("multi_feature_strategy") if obj.get("multi_feature_strategy") is not None else 'concatenate',
            "normalize_features": obj.get("normalize_features") if obj.get("normalize_features") is not None else True,
            "feature_weights": obj.get("feature_weights"),
            "weight_learning_config": WeightLearningConfig.from_dict(obj["weight_learning_config"]) if obj.get("weight_learning_config") is not None else None,
            "output_strategy": obj.get("output_strategy") if obj.get("output_strategy") is not None else 'single',
            "effective_feature_method": obj.get("effective_feature_method") if obj.get("effective_feature_method") is not None else 'mean',
            "enrich_source": obj.get("enrich_source") if obj.get("enrich_source") is not None else False
        })
        return _obj


