# 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
from inspect import getfullargspec
import json
import pprint
import re  # noqa: F401
from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator
from typing import Optional
from mixpeek.models.cursor_pagination_params import CursorPaginationParams
from mixpeek.models.keyset_pagination_params import KeysetPaginationParams
from mixpeek.models.offset_pagination_params import OffsetPaginationParams
from mixpeek.models.scroll_pagination_params import ScrollPaginationParams
from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict
from typing_extensions import Literal, Self
from pydantic import Field

PAGINATION_ANY_OF_SCHEMAS = ["CursorPaginationParams", "KeysetPaginationParams", "OffsetPaginationParams", "ScrollPaginationParams"]

class Pagination(BaseModel):
    """
    Pagination strategy configuration. Defaults to cursor-based pagination with limit=20.   IMPORTANT: Pagination params do NOT support template variables ({{INPUT.x}} or {{DOCUMENT.x}}). Pagination is a request-level parameter for slicing results, separate from pipeline business logic. Pass cursor/limit values directly from your client code. Cursor values come from the previous response's pagination.cursor field.  Supported Methods: - CURSOR (default): Best for infinite scroll, stateless, opaque token - KEYSET: Most efficient, requires stable sort, stateless - OFFSET: Traditional page numbers, can have drift issues - SCROLL: Server-side state, best for bulk exports   Use CURSOR for: - Infinite scroll UIs (mobile apps, feeds, timelines) - Real-time updates where consistency matters - When you can't jump to arbitrary pages   Use KEYSET for: - Maximum performance with large result sets - Stable sort fields (e.g., score DESC, id ASC) - When you need truly stateless pagination   Use OFFSET for: - Traditional page UIs with page numbers - When users need to jump to specific pages - Smaller result sets where drift is acceptable   Use SCROLL for: - Bulk exports or processing large datasets - When you need to iterate through all results - Background jobs with progress tracking   Example (cursor - first page): {\"method\": \"cursor\", \"limit\": 20, \"cursor\": null}  Example (cursor - next page, using cursor from previous response): {\"method\": \"cursor\", \"limit\": 20, \"cursor\": \"eyJvZmZzZXQiOjIwfQ==\"}  Example (offset): {\"method\": \"offset\", \"page_size\": 25, \"page_number\": 2}  Example (keyset): {\"method\": \"keyset\", \"limit\": 20, \"after\": {\"score\": 0.73, \"id\": \"doc_20\"}} 
    """

    # data type: OffsetPaginationParams
    anyof_schema_1_validator: Optional[OffsetPaginationParams] = None
    # data type: CursorPaginationParams
    anyof_schema_2_validator: Optional[CursorPaginationParams] = None
    # data type: ScrollPaginationParams
    anyof_schema_3_validator: Optional[ScrollPaginationParams] = None
    # data type: KeysetPaginationParams
    anyof_schema_4_validator: Optional[KeysetPaginationParams] = None
    if TYPE_CHECKING:
        actual_instance: Optional[Union[CursorPaginationParams, KeysetPaginationParams, OffsetPaginationParams, ScrollPaginationParams]] = None
    else:
        actual_instance: Any = None
    any_of_schemas: Set[str] = { "CursorPaginationParams", "KeysetPaginationParams", "OffsetPaginationParams", "ScrollPaginationParams" }

    model_config = {
        "validate_assignment": True,
        "protected_namespaces": (),
    }

    def __init__(self, *args, **kwargs) -> None:
        if args:
            if len(args) > 1:
                raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
            if kwargs:
                raise ValueError("If a position argument is used, keyword arguments cannot be used.")
            super().__init__(actual_instance=args[0])
        else:
            super().__init__(**kwargs)

    @field_validator('actual_instance')
    def actual_instance_must_validate_anyof(cls, v):
        instance = Pagination.model_construct()
        error_messages = []
        # validate data type: OffsetPaginationParams
        if not isinstance(v, OffsetPaginationParams):
            error_messages.append(f"Error! Input type `{type(v)}` is not `OffsetPaginationParams`")
        else:
            return v

        # validate data type: CursorPaginationParams
        if not isinstance(v, CursorPaginationParams):
            error_messages.append(f"Error! Input type `{type(v)}` is not `CursorPaginationParams`")
        else:
            return v

        # validate data type: ScrollPaginationParams
        if not isinstance(v, ScrollPaginationParams):
            error_messages.append(f"Error! Input type `{type(v)}` is not `ScrollPaginationParams`")
        else:
            return v

        # validate data type: KeysetPaginationParams
        if not isinstance(v, KeysetPaginationParams):
            error_messages.append(f"Error! Input type `{type(v)}` is not `KeysetPaginationParams`")
        else:
            return v

        if error_messages:
            # no match
            raise ValueError("No match found when setting the actual_instance in Pagination with anyOf schemas: CursorPaginationParams, KeysetPaginationParams, OffsetPaginationParams, ScrollPaginationParams. Details: " + ", ".join(error_messages))
        else:
            return v

    @classmethod
    def from_dict(cls, obj: Dict[str, Any]) -> Self:
        return cls.from_json(json.dumps(obj))

    @classmethod
    def from_json(cls, json_str: str) -> Self:
        """Returns the object represented by the json string"""
        instance = cls.model_construct()
        error_messages = []
        # anyof_schema_1_validator: Optional[OffsetPaginationParams] = None
        try:
            instance.actual_instance = OffsetPaginationParams.from_json(json_str)
            return instance
        except (ValidationError, ValueError) as e:
             error_messages.append(str(e))
        # anyof_schema_2_validator: Optional[CursorPaginationParams] = None
        try:
            instance.actual_instance = CursorPaginationParams.from_json(json_str)
            return instance
        except (ValidationError, ValueError) as e:
             error_messages.append(str(e))
        # anyof_schema_3_validator: Optional[ScrollPaginationParams] = None
        try:
            instance.actual_instance = ScrollPaginationParams.from_json(json_str)
            return instance
        except (ValidationError, ValueError) as e:
             error_messages.append(str(e))
        # anyof_schema_4_validator: Optional[KeysetPaginationParams] = None
        try:
            instance.actual_instance = KeysetPaginationParams.from_json(json_str)
            return instance
        except (ValidationError, ValueError) as e:
             error_messages.append(str(e))

        if error_messages:
            # no match
            raise ValueError("No match found when deserializing the JSON string into Pagination with anyOf schemas: CursorPaginationParams, KeysetPaginationParams, OffsetPaginationParams, ScrollPaginationParams. Details: " + ", ".join(error_messages))
        else:
            return instance

    def to_json(self) -> str:
        """Returns the JSON representation of the actual instance"""
        if self.actual_instance is None:
            return "null"

        if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json):
            return self.actual_instance.to_json()
        else:
            return json.dumps(self.actual_instance)

    def to_dict(self) -> Optional[Union[Dict[str, Any], CursorPaginationParams, KeysetPaginationParams, OffsetPaginationParams, ScrollPaginationParams]]:
        """Returns the dict representation of the actual instance"""
        if self.actual_instance is None:
            return None

        if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict):
            return self.actual_instance.to_dict()
        else:
            return self.actual_instance

    def to_str(self) -> str:
        """Returns the string representation of the actual instance"""
        return pprint.pformat(self.model_dump())


