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

from __future__ import annotations
from .preferredmaxlatency import PreferredMaxLatency, PreferredMaxLatencyTypedDict
from .preferredminthroughput import (
    PreferredMinThroughput,
    PreferredMinThroughputTypedDict,
)
from .providername import ProviderName
from .providersort import ProviderSort
from .providersortconfig import ProviderSortConfig, ProviderSortConfigTypedDict
from .quantization import Quantization
from openrouter.types import (
    BaseModel,
    Nullable,
    OptionalNullable,
    UNSET,
    UNSET_SENTINEL,
    UnrecognizedStr,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict


DataCollection = Union[
    Literal[
        "deny",
        "allow",
    ],
    UnrecognizedStr,
]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it

- deny: use only providers which do not collect user data.
"""


IgnoreTypedDict = TypeAliasType("IgnoreTypedDict", Union[ProviderName, str])


Ignore = TypeAliasType(
    "Ignore",
    Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str],
)


class MaxPriceTypedDict(TypedDict):
    r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""

    audio: NotRequired[str]
    completion: NotRequired[str]
    image: NotRequired[str]
    prompt: NotRequired[str]
    r"""Price per million prompt tokens"""
    request: NotRequired[str]


class MaxPrice(BaseModel):
    r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""

    audio: Optional[str] = None

    completion: Optional[str] = None

    image: Optional[str] = None

    prompt: Optional[str] = None
    r"""Price per million prompt tokens"""

    request: Optional[str] = None


OnlyTypedDict = TypeAliasType("OnlyTypedDict", Union[ProviderName, str])


Only = TypeAliasType(
    "Only",
    Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str],
)


OrderTypedDict = TypeAliasType("OrderTypedDict", Union[ProviderName, str])


Order = TypeAliasType(
    "Order",
    Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str],
)


SortTypedDict = TypeAliasType(
    "SortTypedDict", Union[ProviderSortConfigTypedDict, ProviderSort, Any]
)
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""


Sort = TypeAliasType(
    "Sort",
    Union[
        ProviderSortConfig,
        Annotated[ProviderSort, PlainValidator(validate_open_enum(False))],
        Any,
    ],
)
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""


class ProviderPreferencesTypedDict(TypedDict):
    r"""When multiple model providers are available, optionally indicate your routing preference."""

    allow_fallbacks: NotRequired[Nullable[bool]]
    r"""Whether to allow backup providers to serve requests
    - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.
    - false: use only the primary/custom provider, and return the upstream error if it's unavailable.

    """
    data_collection: NotRequired[Nullable[DataCollection]]
    r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
    - allow: (default) allow providers which store user data non-transiently and may train on it

    - deny: use only providers which do not collect user data.
    """
    enforce_distillable_text: NotRequired[Nullable[bool]]
    r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used."""
    ignore: NotRequired[Nullable[List[IgnoreTypedDict]]]
    r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request."""
    max_price: NotRequired[MaxPriceTypedDict]
    r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
    only: NotRequired[Nullable[List[OnlyTypedDict]]]
    r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request."""
    order: NotRequired[Nullable[List[OrderTypedDict]]]
    r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message."""
    preferred_max_latency: NotRequired[Nullable[PreferredMaxLatencyTypedDict]]
    r"""Preferred maximum latency (in seconds). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints above the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold."""
    preferred_min_throughput: NotRequired[Nullable[PreferredMinThroughputTypedDict]]
    r"""Preferred minimum throughput (in tokens per second). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints below the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold."""
    quantizations: NotRequired[Nullable[List[Quantization]]]
    r"""A list of quantization levels to filter the provider by."""
    require_parameters: NotRequired[Nullable[bool]]
    r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest."""
    sort: NotRequired[Nullable[SortTypedDict]]
    r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
    zdr: NotRequired[Nullable[bool]]
    r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used."""


class ProviderPreferences(BaseModel):
    r"""When multiple model providers are available, optionally indicate your routing preference."""

    allow_fallbacks: OptionalNullable[bool] = UNSET
    r"""Whether to allow backup providers to serve requests
    - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.
    - false: use only the primary/custom provider, and return the upstream error if it's unavailable.

    """

    data_collection: Annotated[
        OptionalNullable[DataCollection], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
    - allow: (default) allow providers which store user data non-transiently and may train on it

    - deny: use only providers which do not collect user data.
    """

    enforce_distillable_text: OptionalNullable[bool] = UNSET
    r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used."""

    ignore: OptionalNullable[List[Ignore]] = UNSET
    r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request."""

    max_price: Optional[MaxPrice] = None
    r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""

    only: OptionalNullable[List[Only]] = UNSET
    r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request."""

    order: OptionalNullable[List[Order]] = UNSET
    r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message."""

    preferred_max_latency: OptionalNullable[PreferredMaxLatency] = UNSET
    r"""Preferred maximum latency (in seconds). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints above the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold."""

    preferred_min_throughput: OptionalNullable[PreferredMinThroughput] = UNSET
    r"""Preferred minimum throughput (in tokens per second). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints below the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold."""

    quantizations: OptionalNullable[
        List[Annotated[Quantization, PlainValidator(validate_open_enum(False))]]
    ] = UNSET
    r"""A list of quantization levels to filter the provider by."""

    require_parameters: OptionalNullable[bool] = UNSET
    r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest."""

    sort: OptionalNullable[Sort] = UNSET
    r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""

    zdr: OptionalNullable[bool] = UNSET
    r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "allow_fallbacks",
            "data_collection",
            "enforce_distillable_text",
            "ignore",
            "max_price",
            "only",
            "order",
            "preferred_max_latency",
            "preferred_min_throughput",
            "quantizations",
            "require_parameters",
            "sort",
            "zdr",
        ]
        nullable_fields = [
            "allow_fallbacks",
            "data_collection",
            "enforce_distillable_text",
            "ignore",
            "only",
            "order",
            "preferred_max_latency",
            "preferred_min_throughput",
            "quantizations",
            "require_parameters",
            "sort",
            "zdr",
        ]
        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
