"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from __future__ import annotations
from openrouter.components import providerpreferences as components_providerpreferences
from openrouter.types import (
    BaseModel,
    Nullable,
    OptionalNullable,
    UNSET,
    UNSET_SENTINEL,
)
from openrouter.utils import FieldMetadata, HeaderMetadata, RequestMetadata
import pydantic
from pydantic import model_serializer
from typing import List, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict


class CreateRerankGlobalsTypedDict(TypedDict):
    http_referer: NotRequired[str]
    r"""The app identifier should be your app's URL and is used as the primary identifier for rankings.
    This is used to track API usage per application.

    """
    x_open_router_title: NotRequired[str]
    r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard.

    """
    x_open_router_categories: NotRequired[str]
    r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.

    """


class CreateRerankGlobals(BaseModel):
    http_referer: Annotated[
        Optional[str],
        pydantic.Field(alias="HTTP-Referer"),
        FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
    ] = None
    r"""The app identifier should be your app's URL and is used as the primary identifier for rankings.
    This is used to track API usage per application.

    """

    x_open_router_title: Annotated[
        Optional[str],
        pydantic.Field(alias="X-OpenRouter-Title"),
        FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
    ] = None
    r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard.

    """

    x_open_router_categories: Annotated[
        Optional[str],
        pydantic.Field(alias="X-OpenRouter-Categories"),
        FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
    ] = None
    r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.

    """


class DocumentRequestTypedDict(TypedDict):
    r"""A structured document with optional text and/or image content. At least one of `text` or `image` must be provided."""

    image: NotRequired[str]
    r"""An image associated with the document, as a remote URL (http/https) or a base64-encoded data URI (data:image/...)."""
    text: NotRequired[str]
    r"""The document text"""


class DocumentRequest(BaseModel):
    r"""A structured document with optional text and/or image content. At least one of `text` or `image` must be provided."""

    image: Optional[str] = None
    r"""An image associated with the document, as a remote URL (http/https) or a base64-encoded data URI (data:image/...)."""

    text: Optional[str] = None
    r"""The document text"""


DocumentTypedDict = TypeAliasType(
    "DocumentTypedDict", Union[DocumentRequestTypedDict, str]
)
r"""A document to rerank. Either a plain string, or a structured object with optional `text` and/or `image`."""


Document = TypeAliasType("Document", Union[DocumentRequest, str])
r"""A document to rerank. Either a plain string, or a structured object with optional `text` and/or `image`."""


class CreateRerankRequestBodyTypedDict(TypedDict):
    r"""Rerank request input"""

    documents: List[DocumentTypedDict]
    r"""The list of documents to rerank. Documents may be plain strings, or structured objects with `text` and/or `image` for multimodal models."""
    model: str
    r"""The rerank model to use"""
    query: str
    r"""The search query to rerank documents against"""
    provider: NotRequired[
        Nullable[components_providerpreferences.ProviderPreferencesTypedDict]
    ]
    top_n: NotRequired[int]
    r"""Number of most relevant documents to return"""


class CreateRerankRequestBody(BaseModel):
    r"""Rerank request input"""

    documents: List[Document]
    r"""The list of documents to rerank. Documents may be plain strings, or structured objects with `text` and/or `image` for multimodal models."""

    model: str
    r"""The rerank model to use"""

    query: str
    r"""The search query to rerank documents against"""

    provider: OptionalNullable[components_providerpreferences.ProviderPreferences] = (
        UNSET
    )

    top_n: Optional[int] = None
    r"""Number of most relevant documents to return"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["provider", "top_n"]
        nullable_fields = ["provider"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class CreateRerankRequestTypedDict(TypedDict):
    request_body: CreateRerankRequestBodyTypedDict
    http_referer: NotRequired[str]
    r"""The app identifier should be your app's URL and is used as the primary identifier for rankings.
    This is used to track API usage per application.

    """
    x_open_router_title: NotRequired[str]
    r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard.

    """
    x_open_router_categories: NotRequired[str]
    r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.

    """


class CreateRerankRequest(BaseModel):
    request_body: Annotated[
        CreateRerankRequestBody,
        FieldMetadata(request=RequestMetadata(media_type="application/json")),
    ]

    http_referer: Annotated[
        Optional[str],
        pydantic.Field(alias="HTTP-Referer"),
        FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
    ] = None
    r"""The app identifier should be your app's URL and is used as the primary identifier for rankings.
    This is used to track API usage per application.

    """

    x_open_router_title: Annotated[
        Optional[str],
        pydantic.Field(alias="X-OpenRouter-Title"),
        FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
    ] = None
    r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard.

    """

    x_open_router_categories: Annotated[
        Optional[str],
        pydantic.Field(alias="X-OpenRouter-Categories"),
        FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
    ] = None
    r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.

    """


class DocumentResponseTypedDict(TypedDict):
    r"""The document object echoing the original input (text and/or image)"""

    image: NotRequired[str]
    r"""The image (URL or data URI) from the original document"""
    text: NotRequired[str]
    r"""The document text"""


class DocumentResponse(BaseModel):
    r"""The document object echoing the original input (text and/or image)"""

    image: Optional[str] = None
    r"""The image (URL or data URI) from the original document"""

    text: Optional[str] = None
    r"""The document text"""


class ResultTypedDict(TypedDict):
    r"""A single rerank result"""

    document: DocumentResponseTypedDict
    r"""The document object echoing the original input (text and/or image)"""
    index: int
    r"""Index of the document in the original input list"""
    relevance_score: float
    r"""Relevance score of the document to the query"""


class Result(BaseModel):
    r"""A single rerank result"""

    document: DocumentResponse
    r"""The document object echoing the original input (text and/or image)"""

    index: int
    r"""Index of the document in the original input list"""

    relevance_score: float
    r"""Relevance score of the document to the query"""


class CreateRerankUsageTypedDict(TypedDict):
    r"""Usage statistics"""

    cost: NotRequired[float]
    r"""Cost of the request in credits"""
    search_units: NotRequired[int]
    r"""Number of search units consumed (Cohere billing)"""
    total_tokens: NotRequired[int]
    r"""Total number of tokens used"""


class CreateRerankUsage(BaseModel):
    r"""Usage statistics"""

    cost: Optional[float] = None
    r"""Cost of the request in credits"""

    search_units: Optional[int] = None
    r"""Number of search units consumed (Cohere billing)"""

    total_tokens: Optional[int] = None
    r"""Total number of tokens used"""


class CreateRerankResponseBodyTypedDict(TypedDict):
    r"""Rerank response containing ranked results"""

    model: str
    r"""The model used for reranking"""
    results: List[ResultTypedDict]
    r"""List of rerank results sorted by relevance"""
    id: NotRequired[str]
    r"""Unique identifier for the rerank response (ORID format)"""
    provider: NotRequired[str]
    r"""The provider that served the rerank request"""
    usage: NotRequired[CreateRerankUsageTypedDict]
    r"""Usage statistics"""


class CreateRerankResponseBody(BaseModel):
    r"""Rerank response containing ranked results"""

    model: str
    r"""The model used for reranking"""

    results: List[Result]
    r"""List of rerank results sorted by relevance"""

    id: Optional[str] = None
    r"""Unique identifier for the rerank response (ORID format)"""

    provider: Optional[str] = None
    r"""The provider that served the rerank request"""

    usage: Optional[CreateRerankUsage] = None
    r"""Usage statistics"""


CreateRerankResponseTypedDict = TypeAliasType(
    "CreateRerankResponseTypedDict", Union[CreateRerankResponseBodyTypedDict, str]
)


CreateRerankResponse = TypeAliasType(
    "CreateRerankResponse", Union[CreateRerankResponseBody, str]
)
