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

from __future__ import annotations
from datetime import datetime
from openrouter.types import BaseModel, UnrecognizedStr
from openrouter.utils import (
    FieldMetadata,
    HeaderMetadata,
    RequestMetadata,
    validate_open_enum,
)
import pydantic
from pydantic.functional_validators import PlainValidator
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict


class QueryAnalyticsGlobalsTypedDict(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 QueryAnalyticsGlobals(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.

    """


Value2TypedDict = TypeAliasType("Value2TypedDict", Union[str, float])


Value2 = TypeAliasType("Value2", Union[str, float])


Value1TypedDict = TypeAliasType(
    "Value1TypedDict", Union[str, float, List[Value2TypedDict]]
)
r"""Filter value (scalar or array depending on operator). Several dimensions are enriched in responses (returned as human-readable labels), but filters must use the underlying ID: `api_key_id` — numeric ID (from generation metadata) or key hash (64-char hex from GET /api/v1/keys, resolved server-side); `user` — Clerk user ID (e.g. \"user_abc123\"), not the display name; `workspace` — workspace UUID, not the workspace name; `app` — numeric app ID, not the app title; `model` — permaslug (e.g. \"openai/gpt-4o\"), not the display name. Other dimensions (provider, origin, country, etc.) are not enriched and accept the value as returned."""


Value1 = TypeAliasType("Value1", Union[str, float, List[Value2]])
r"""Filter value (scalar or array depending on operator). Several dimensions are enriched in responses (returned as human-readable labels), but filters must use the underlying ID: `api_key_id` — numeric ID (from generation metadata) or key hash (64-char hex from GET /api/v1/keys, resolved server-side); `user` — Clerk user ID (e.g. \"user_abc123\"), not the display name; `workspace` — workspace UUID, not the workspace name; `app` — numeric app ID, not the app title; `model` — permaslug (e.g. \"openai/gpt-4o\"), not the display name. Other dimensions (provider, origin, country, etc.) are not enriched and accept the value as returned."""


class FilterTypedDict(TypedDict):
    field: str
    r"""Dimension to filter on. Use the /meta endpoint for available dimensions."""
    operator: str
    r"""Filter operator"""
    value: Value1TypedDict
    r"""Filter value (scalar or array depending on operator). Several dimensions are enriched in responses (returned as human-readable labels), but filters must use the underlying ID: `api_key_id` — numeric ID (from generation metadata) or key hash (64-char hex from GET /api/v1/keys, resolved server-side); `user` — Clerk user ID (e.g. \"user_abc123\"), not the display name; `workspace` — workspace UUID, not the workspace name; `app` — numeric app ID, not the app title; `model` — permaslug (e.g. \"openai/gpt-4o\"), not the display name. Other dimensions (provider, origin, country, etc.) are not enriched and accept the value as returned."""


class Filter(BaseModel):
    field: str
    r"""Dimension to filter on. Use the /meta endpoint for available dimensions."""

    operator: str
    r"""Filter operator"""

    value: Value1
    r"""Filter value (scalar or array depending on operator). Several dimensions are enriched in responses (returned as human-readable labels), but filters must use the underlying ID: `api_key_id` — numeric ID (from generation metadata) or key hash (64-char hex from GET /api/v1/keys, resolved server-side); `user` — Clerk user ID (e.g. \"user_abc123\"), not the display name; `workspace` — workspace UUID, not the workspace name; `app` — numeric app ID, not the app title; `model` — permaslug (e.g. \"openai/gpt-4o\"), not the display name. Other dimensions (provider, origin, country, etc.) are not enriched and accept the value as returned."""


Direction = Union[
    Literal[
        "asc",
        "desc",
    ],
    UnrecognizedStr,
]


class OrderByTypedDict(TypedDict):
    direction: Direction
    field: str
    r"""Field to order by"""


class OrderBy(BaseModel):
    direction: Annotated[Direction, PlainValidator(validate_open_enum(False))]

    field: str
    r"""Field to order by"""


class TimeRangeTypedDict(TypedDict):
    end: datetime
    start: datetime


class TimeRange(BaseModel):
    end: datetime

    start: datetime


class QueryAnalyticsRequestBodyTypedDict(TypedDict):
    metrics: List[str]
    dimensions: NotRequired[List[str]]
    filters: NotRequired[List[FilterTypedDict]]
    granularity: NotRequired[str]
    r"""Time granularity"""
    group_limit: NotRequired[int]
    r"""Maximum rows per distinct combination of dimensions. When omitted on time-series queries (granularity + dimensions), auto-computed to avoid truncating time windows. Explicit values override the default and may truncate time buckets if set lower than the number of buckets in the range. Ignored when no dimensions are specified."""
    limit: NotRequired[int]
    r"""Maximum total rows returned. Defaults to 1000. On time-series queries with dimensions and no explicit group_limit, the server may raise this to accommodate the expected number of unique time-bucket/dimension combinations."""
    order_by: NotRequired[OrderByTypedDict]
    time_range: NotRequired[TimeRangeTypedDict]


class QueryAnalyticsRequestBody(BaseModel):
    metrics: List[str]

    dimensions: Optional[List[str]] = None

    filters: Optional[List[Filter]] = None

    granularity: Optional[str] = None
    r"""Time granularity"""

    group_limit: Optional[int] = None
    r"""Maximum rows per distinct combination of dimensions. When omitted on time-series queries (granularity + dimensions), auto-computed to avoid truncating time windows. Explicit values override the default and may truncate time buckets if set lower than the number of buckets in the range. Ignored when no dimensions are specified."""

    limit: Optional[int] = None
    r"""Maximum total rows returned. Defaults to 1000. On time-series queries with dimensions and no explicit group_limit, the server may raise this to accommodate the expected number of unique time-bucket/dimension combinations."""

    order_by: Optional[OrderBy] = None

    time_range: Optional[TimeRange] = None


class QueryAnalyticsRequestTypedDict(TypedDict):
    request_body: QueryAnalyticsRequestBodyTypedDict
    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 QueryAnalyticsRequest(BaseModel):
    request_body: Annotated[
        QueryAnalyticsRequestBody,
        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 QueryAnalyticsData1TypedDict(TypedDict):
    r"""A row of analytics data with metric/dimension values"""


class QueryAnalyticsData1(BaseModel):
    r"""A row of analytics data with metric/dimension values"""


class MetadataTypedDict(TypedDict):
    query_time_ms: float
    row_count: int
    truncated: bool


class Metadata(BaseModel):
    query_time_ms: float

    row_count: int

    truncated: bool


class QueryAnalyticsData2TypedDict(TypedDict):
    data: List[QueryAnalyticsData1TypedDict]
    metadata: MetadataTypedDict
    cached_at: NotRequired[float]
    warnings: NotRequired[List[str]]
    r"""Warnings about filter resolution issues (e.g. unresolvable api_key_id hashes). The query still runs normally; these inform the caller that some filter values could not be resolved."""


class QueryAnalyticsData2(BaseModel):
    data: List[QueryAnalyticsData1]

    metadata: Metadata

    cached_at: Annotated[Optional[float], pydantic.Field(alias="cachedAt")] = None

    warnings: Optional[List[str]] = None
    r"""Warnings about filter resolution issues (e.g. unresolvable api_key_id hashes). The query still runs normally; these inform the caller that some filter values could not be resolved."""


class QueryAnalyticsResponseTypedDict(TypedDict):
    r"""Analytics query results"""

    data: QueryAnalyticsData2TypedDict


class QueryAnalyticsResponse(BaseModel):
    r"""Analytics query results"""

    data: QueryAnalyticsData2
