# 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, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from mixpeek.models.sort_direction import SortDirection
from typing import Optional, Set
from typing_extensions import Self

class StageParamsSortAttribute(BaseModel):
    """
    Configuration for sorting documents by an attribute field.  **Stage Category**: SORT  **Transformation**: N documents → N documents (same docs, different order, same schema)  **Purpose**: Reorders documents in the pipeline based on any document attribute (not just relevance scores). Use this for sorting by metadata fields like dates, popularity, priority, or custom attributes.  **When to Use**:     - Sort by timestamps (created_at, updated_at, published_date)     - Sort by numeric metadata (popularity, view_count, rating, price)     - Sort by string attributes (title, category) with optional case-insensitive comparison     - Apply business logic ordering (priority, status)     - Secondary sorting after relevance-based retrieval  **When NOT to Use**:     - For sorting by relevance/similarity scores (use sort_relevance instead)     - For initial document retrieval (use FILTER stages)     - For removing documents (use FILTER stages)     - For enriching documents (use APPLY stages)  **Operational Behavior**:     - Operates on in-memory document results (no database queries)     - Maintains all documents, just changes their order     - Fast operation (simple in-memory sort)     - Does not change document count or schema     - Handles null values gracefully (configurable placement)  **Common Pipeline Position**: FILTER → SORT (this stage) → APPLY  Requirements:     - field: REQUIRED, document field path to sort on     - direction: OPTIONAL, defaults to descending     - nulls_last: OPTIONAL, defaults to true (nulls at end)  Use Cases:     - Recent content first: Sort by published_date desc     - Popular content: Sort by view_count or popularity score     - Alphabetical: Sort by title or name     - Priority-based: Sort by urgency or importance ratings     - Temporal ordering: Sort by event timestamps
    """ # noqa: E501
    var_field: Optional[StrictStr] = Field(default='metadata.created_at', description="Document field path to sort on. Use dot notation for nested fields (e.g., 'metadata.release_date'). Supports template expressions for dynamic field selection. Can sort by strings, numbers, dates, or booleans. Examples: 'metadata.created_at', 'metadata.popularity', 'title'.", alias="field")
    direction: Optional[SortDirection] = Field(default=None, description="OPTIONAL. Sort direction. 'desc' (default): Highest/latest values first (Z-A, 100-0, newest-oldest). 'asc': Lowest/earliest values first (A-Z, 0-100, oldest-newest).")
    nulls_last: Optional[StrictBool] = Field(default=True, description="OPTIONAL. Whether documents with null/missing field values should be placed at the end of results regardless of sort direction. true (default): Nulls always at the end. false: Nulls follow natural sort order (beginning for asc, end for desc).")
    __properties: ClassVar[List[str]] = ["field", "direction", "nulls_last"]

    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 StageParamsSortAttribute 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 StageParamsSortAttribute from a dict"""
        if obj is None:
            return None

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

        _obj = cls.model_validate({
            "field": obj.get("field") if obj.get("field") is not None else 'metadata.created_at',
            "direction": obj.get("direction"),
            "nulls_last": obj.get("nulls_last") if obj.get("nulls_last") is not None else True
        })
        return _obj


