# coding: utf-8

"""
    Amalgam Index API

    Amalgam Index (Amgix). Open-Source Hybrid Search System

    The version of the OpenAPI document: 1.1.0
    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 amgix_client.models.custom_vector import CustomVector
from amgix_client.models.metadata_filter import MetadataFilter
from amgix_client.models.vector_search_weight import VectorSearchWeight
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python

class SearchQuery(BaseModel):
    """
    Configuration for a search query. Defines the query string and vector weights. This is the model that will be sent by end users to the search API endpoint.
    """ # noqa: E501
    query: Annotated[str, Field(strict=True, max_length=10000)] = Field(description="The search query string (max 10000 characters)")
    vector_weights: Optional[List[VectorSearchWeight]] = Field(default=None, description="List of vectors, fields, and weights to use for searching. If empty, equal weights will be auto-generated for all available vectors.")
    custom_vectors: Optional[List[CustomVector]] = Field(default=None, description="Pre-generated custom vectors for this search query (optional)")
    limit: Optional[Annotated[int, Field(le=100, strict=True, ge=1)]] = Field(default=10, description="Maximum number of results to return (1 to 100)")
    score_threshold: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Optional minimum score threshold. Results below this score will be excluded")
    document_tags: Optional[Annotated[List[StrictStr], Field(max_length=50)]] = Field(default=None, description="Optional filter to include only documents with specific tags (max 50 tags, each max 100 characters; cannot contain pipe characters)")
    document_tags_match_all: Optional[StrictBool] = Field(default=False, description="If True, documents must have ALL specified tags (AND). If False, documents must have ANY of the specified tags (OR).")
    metadata_filter: Optional[MetadataFilter] = Field(default=None, description="Optional recursive metadata filter. Only fields declared in collection metadata_indexes can be filtered.")
    raw_scores: Optional[StrictBool] = Field(default=False, description="Whether to include individual vector scores in results")
    wmtr_trigram_weight: Optional[Union[StrictFloat, StrictInt]] = Field(default=1.0, description="WMTR trigram channel multiplier for this search query.")
    fusion_mode: Optional[StrictStr] = Field(default='rrf', description="How to combine multi-vector search results. 'rrf' = reciprocal rank fusion (rank-based). 'linear' = min-max normalize each retriever's scores on its prefetch list, then sum weight * normalized score.")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["query", "vector_weights", "custom_vectors", "limit", "score_threshold", "document_tags", "document_tags_match_all", "metadata_filter", "raw_scores", "wmtr_trigram_weight", "fusion_mode"]

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

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

    model_config = ConfigDict(
        validate_by_name=True,
        validate_by_alias=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"""
        return json.dumps(to_jsonable_python(self.to_dict()))

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of SearchQuery 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.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _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 vector_weights (list)
        _items = []
        if self.vector_weights:
            for _item_vector_weights in self.vector_weights:
                if _item_vector_weights:
                    _items.append(_item_vector_weights.to_dict())
            _dict['vector_weights'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in custom_vectors (list)
        _items = []
        if self.custom_vectors:
            for _item_custom_vectors in self.custom_vectors:
                if _item_custom_vectors:
                    _items.append(_item_custom_vectors.to_dict())
            _dict['custom_vectors'] = _items
        # override the default output from pydantic by calling `to_dict()` of metadata_filter
        if self.metadata_filter:
            _dict['metadata_filter'] = self.metadata_filter.to_dict()
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        return _dict

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

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

        _obj = cls.model_validate({
            "query": obj.get("query"),
            "vector_weights": [VectorSearchWeight.from_dict(_item) for _item in obj["vector_weights"]] if obj.get("vector_weights") is not None else None,
            "custom_vectors": [CustomVector.from_dict(_item) for _item in obj["custom_vectors"]] if obj.get("custom_vectors") is not None else None,
            "limit": obj.get("limit") if obj.get("limit") is not None else 10,
            "score_threshold": obj.get("score_threshold"),
            "document_tags": obj.get("document_tags"),
            "document_tags_match_all": obj.get("document_tags_match_all") if obj.get("document_tags_match_all") is not None else False,
            "metadata_filter": MetadataFilter.from_dict(obj["metadata_filter"]) if obj.get("metadata_filter") is not None else None,
            "raw_scores": obj.get("raw_scores") if obj.get("raw_scores") is not None else False,
            "wmtr_trigram_weight": obj.get("wmtr_trigram_weight") if obj.get("wmtr_trigram_weight") is not None else 1.0,
            "fusion_mode": obj.get("fusion_mode") if obj.get("fusion_mode") is not None else 'rrf'
        })
        # store additional fields in additional_properties
        for _key in obj.keys():
            if _key not in cls.__properties:
                _obj.additional_properties[_key] = obj.get(_key)

        return _obj


