# This file was auto-generated by Fern from our API Definition.

import datetime as dt
import typing
from json.decoder import JSONDecodeError

from ..commons.errors.access_denied_error import AccessDeniedError
from ..commons.errors.error import Error
from ..commons.errors.method_not_allowed_error import MethodNotAllowedError
from ..commons.errors.not_found_error import NotFoundError
from ..commons.errors.unauthorized_error import UnauthorizedError
from ..commons.types.observation_level import ObservationLevel
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.datetime_utils import serialize_datetime
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from .types.observations_v2response import ObservationsV2Response


class RawObservationsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def get_many(
        self,
        *,
        fields: typing.Optional[str] = None,
        expand_metadata: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        parse_io_as_json: typing.Optional[bool] = None,
        name: typing.Optional[str] = None,
        user_id: typing.Optional[str] = None,
        type: typing.Optional[str] = None,
        trace_id: typing.Optional[str] = None,
        level: typing.Optional[ObservationLevel] = None,
        parent_observation_id: typing.Optional[str] = None,
        environment: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        from_start_time: typing.Optional[dt.datetime] = None,
        to_start_time: typing.Optional[dt.datetime] = None,
        version: typing.Optional[str] = None,
        filter: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ObservationsV2Response]:
        """
        Get a list of observations with cursor-based pagination and flexible field selection.

        ## Cursor-based Pagination
        This endpoint uses cursor-based pagination for efficient traversal of large datasets.
        The cursor is returned in the response metadata and should be passed in subsequent requests
        to retrieve the next page of results.

        ## Field Selection
        Use the `fields` parameter to control which observation fields are returned:
        - `core` - Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type
        - `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId
        - `time` - completionStartTime, createdAt, updatedAt
        - `io` - input, output
        - `metadata` - metadata (truncated to 200 chars by default, use `expandMetadata` to get full values)
        - `model` - providedModelName, internalModelId, modelParameters
        - `usage` - usageDetails, costDetails, totalCost
        - `prompt` - promptId, promptName, promptVersion
        - `metrics` - latency, timeToFirstToken

        If not specified, `core` and `basic` field groups are returned.

        ## Filters
        Multiple filtering options are available via query parameters or the structured `filter` parameter.
        When using the `filter` parameter, it takes precedence over individual query parameter filters.

        Parameters
        ----------
        fields : typing.Optional[str]
            Comma-separated list of field groups to include in the response.
            Available groups: core, basic, time, io, metadata, model, usage, prompt, metrics.
            If not specified, `core` and `basic` field groups are returned.
            Example: "basic,usage,model"

        expand_metadata : typing.Optional[str]
            Comma-separated list of metadata keys to return non-truncated.
            By default, metadata values over 200 characters are truncated.
            Use this parameter to retrieve full values for specific keys.
            Example: "key1,key2"

        limit : typing.Optional[int]
            Number of items to return per page. Maximum 1000, default 50.

        cursor : typing.Optional[str]
            Base64-encoded cursor for pagination. Use the cursor from the previous response to get the next page.

        parse_io_as_json : typing.Optional[bool]
            **Deprecated.** Setting this to `true` will return a 400 error.
            Input/output fields are always returned as raw strings.
            Remove this parameter or set it to `false`.

        name : typing.Optional[str]

        user_id : typing.Optional[str]

        type : typing.Optional[str]
            Filter by observation type (e.g., "GENERATION", "SPAN", "EVENT", "AGENT", "TOOL", "CHAIN", "RETRIEVER", "EVALUATOR", "EMBEDDING", "GUARDRAIL")

        trace_id : typing.Optional[str]

        level : typing.Optional[ObservationLevel]
            Optional filter for observations with a specific level (e.g. "DEBUG", "DEFAULT", "WARNING", "ERROR").

        parent_observation_id : typing.Optional[str]

        environment : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Optional filter for observations where the environment is one of the provided values.

        from_start_time : typing.Optional[dt.datetime]
            Retrieve only observations with a start_time on or after this datetime (ISO 8601).

        to_start_time : typing.Optional[dt.datetime]
            Retrieve only observations with a start_time before this datetime (ISO 8601).

        version : typing.Optional[str]
            Optional filter to only include observations with a certain version.

        filter : typing.Optional[str]
            JSON string containing an array of filter conditions. When provided, this takes precedence over query parameter filters (userId, name, type, level, environment, fromStartTime, ...).

            ## Filter Structure
            Each filter condition has the following structure:
            ```json
            [
              {
                "type": string,           // Required. One of: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "boolean", "null"
                "column": string,         // Required. Column to filter on (see available columns below)
                "operator": string,       // Required. Operator based on type:
                                          // - datetime: ">", "<", ">=", "<="
                                          // - string: "=", "contains", "does not contain", "starts with", "ends with"
                                          // - stringOptions: "any of", "none of"
                                          // - categoryOptions: "any of", "none of"
                                          // - arrayOptions: "any of", "none of", "all of"
                                          // - number: "=", ">", "<", ">=", "<="
                                          // - stringObject: "=", "contains", "does not contain", "starts with", "ends with"
                                          // - numberObject: "=", ">", "<", ">=", "<="
                                          // - boolean: "=", "<>"
                                          // - null: "is null", "is not null"
                "value": any,             // Required (except for null type). Value to compare against. Type depends on filter type
                "key": string             // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata
              }
            ]
            ```

            ## Available Columns

            ### Core Observation Fields
            - `id` (string) - Observation ID
            - `type` (string) - Observation type (SPAN, GENERATION, EVENT)
            - `name` (string) - Observation name
            - `traceId` (string) - Associated trace ID
            - `startTime` (datetime) - Observation start time
            - `endTime` (datetime) - Observation end time
            - `environment` (string) - Environment tag
            - `level` (string) - Log level (DEBUG, DEFAULT, WARNING, ERROR)
            - `statusMessage` (string) - Status message
            - `version` (string) - Version tag
            - `userId` (string) - User ID
            - `sessionId` (string) - Session ID

            ### Trace-Related Fields
            - `traceName` (string) - Name of the parent trace
            - `traceTags` (arrayOptions) - Tags from the parent trace
            - `tags` (arrayOptions) - Alias for traceTags

            ### Performance Metrics
            - `latency` (number) - Latency in seconds (calculated: end_time - start_time)
            - `timeToFirstToken` (number) - Time to first token in seconds
            - `tokensPerSecond` (number) - Output tokens per second

            ### Token Usage
            - `inputTokens` (number) - Number of input tokens
            - `outputTokens` (number) - Number of output tokens
            - `totalTokens` (number) - Total tokens (alias: `tokens`)

            ### Cost Metrics
            - `inputCost` (number) - Input cost in USD
            - `outputCost` (number) - Output cost in USD
            - `totalCost` (number) - Total cost in USD

            ### Model Information
            - `model` (string) - Provided model name (alias: `providedModelName`)
            - `promptName` (string) - Associated prompt name
            - `promptVersion` (number) - Associated prompt version

            ### Structured Data
            - `metadata` (stringObject/numberObject/categoryOptions) - Metadata key-value pairs. Use `key` parameter to filter on specific metadata keys.

            ## Filter Examples
            ```json
            [
              {
                "type": "string",
                "column": "type",
                "operator": "=",
                "value": "GENERATION"
              },
              {
                "type": "number",
                "column": "latency",
                "operator": ">=",
                "value": 2.5
              },
              {
                "type": "stringObject",
                "column": "metadata",
                "key": "environment",
                "operator": "=",
                "value": "production"
              }
            ]
            ```

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ObservationsV2Response]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/public/v2/observations",
            method="GET",
            params={
                "fields": fields,
                "expandMetadata": expand_metadata,
                "limit": limit,
                "cursor": cursor,
                "parseIoAsJson": parse_io_as_json,
                "name": name,
                "userId": user_id,
                "type": type,
                "traceId": trace_id,
                "level": level,
                "parentObservationId": parent_observation_id,
                "environment": environment,
                "fromStartTime": serialize_datetime(from_start_time)
                if from_start_time is not None
                else None,
                "toStartTime": serialize_datetime(to_start_time)
                if to_start_time is not None
                else None,
                "version": version,
                "filter": filter,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ObservationsV2Response,
                    parse_obj_as(
                        type_=ObservationsV2Response,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(
                status_code=_response.status_code,
                headers=dict(_response.headers),
                body=_response.text,
            )
        raise ApiError(
            status_code=_response.status_code,
            headers=dict(_response.headers),
            body=_response_json,
        )


class AsyncRawObservationsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_many(
        self,
        *,
        fields: typing.Optional[str] = None,
        expand_metadata: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        parse_io_as_json: typing.Optional[bool] = None,
        name: typing.Optional[str] = None,
        user_id: typing.Optional[str] = None,
        type: typing.Optional[str] = None,
        trace_id: typing.Optional[str] = None,
        level: typing.Optional[ObservationLevel] = None,
        parent_observation_id: typing.Optional[str] = None,
        environment: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        from_start_time: typing.Optional[dt.datetime] = None,
        to_start_time: typing.Optional[dt.datetime] = None,
        version: typing.Optional[str] = None,
        filter: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ObservationsV2Response]:
        """
        Get a list of observations with cursor-based pagination and flexible field selection.

        ## Cursor-based Pagination
        This endpoint uses cursor-based pagination for efficient traversal of large datasets.
        The cursor is returned in the response metadata and should be passed in subsequent requests
        to retrieve the next page of results.

        ## Field Selection
        Use the `fields` parameter to control which observation fields are returned:
        - `core` - Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type
        - `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId
        - `time` - completionStartTime, createdAt, updatedAt
        - `io` - input, output
        - `metadata` - metadata (truncated to 200 chars by default, use `expandMetadata` to get full values)
        - `model` - providedModelName, internalModelId, modelParameters
        - `usage` - usageDetails, costDetails, totalCost
        - `prompt` - promptId, promptName, promptVersion
        - `metrics` - latency, timeToFirstToken

        If not specified, `core` and `basic` field groups are returned.

        ## Filters
        Multiple filtering options are available via query parameters or the structured `filter` parameter.
        When using the `filter` parameter, it takes precedence over individual query parameter filters.

        Parameters
        ----------
        fields : typing.Optional[str]
            Comma-separated list of field groups to include in the response.
            Available groups: core, basic, time, io, metadata, model, usage, prompt, metrics.
            If not specified, `core` and `basic` field groups are returned.
            Example: "basic,usage,model"

        expand_metadata : typing.Optional[str]
            Comma-separated list of metadata keys to return non-truncated.
            By default, metadata values over 200 characters are truncated.
            Use this parameter to retrieve full values for specific keys.
            Example: "key1,key2"

        limit : typing.Optional[int]
            Number of items to return per page. Maximum 1000, default 50.

        cursor : typing.Optional[str]
            Base64-encoded cursor for pagination. Use the cursor from the previous response to get the next page.

        parse_io_as_json : typing.Optional[bool]
            **Deprecated.** Setting this to `true` will return a 400 error.
            Input/output fields are always returned as raw strings.
            Remove this parameter or set it to `false`.

        name : typing.Optional[str]

        user_id : typing.Optional[str]

        type : typing.Optional[str]
            Filter by observation type (e.g., "GENERATION", "SPAN", "EVENT", "AGENT", "TOOL", "CHAIN", "RETRIEVER", "EVALUATOR", "EMBEDDING", "GUARDRAIL")

        trace_id : typing.Optional[str]

        level : typing.Optional[ObservationLevel]
            Optional filter for observations with a specific level (e.g. "DEBUG", "DEFAULT", "WARNING", "ERROR").

        parent_observation_id : typing.Optional[str]

        environment : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Optional filter for observations where the environment is one of the provided values.

        from_start_time : typing.Optional[dt.datetime]
            Retrieve only observations with a start_time on or after this datetime (ISO 8601).

        to_start_time : typing.Optional[dt.datetime]
            Retrieve only observations with a start_time before this datetime (ISO 8601).

        version : typing.Optional[str]
            Optional filter to only include observations with a certain version.

        filter : typing.Optional[str]
            JSON string containing an array of filter conditions. When provided, this takes precedence over query parameter filters (userId, name, type, level, environment, fromStartTime, ...).

            ## Filter Structure
            Each filter condition has the following structure:
            ```json
            [
              {
                "type": string,           // Required. One of: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "boolean", "null"
                "column": string,         // Required. Column to filter on (see available columns below)
                "operator": string,       // Required. Operator based on type:
                                          // - datetime: ">", "<", ">=", "<="
                                          // - string: "=", "contains", "does not contain", "starts with", "ends with"
                                          // - stringOptions: "any of", "none of"
                                          // - categoryOptions: "any of", "none of"
                                          // - arrayOptions: "any of", "none of", "all of"
                                          // - number: "=", ">", "<", ">=", "<="
                                          // - stringObject: "=", "contains", "does not contain", "starts with", "ends with"
                                          // - numberObject: "=", ">", "<", ">=", "<="
                                          // - boolean: "=", "<>"
                                          // - null: "is null", "is not null"
                "value": any,             // Required (except for null type). Value to compare against. Type depends on filter type
                "key": string             // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata
              }
            ]
            ```

            ## Available Columns

            ### Core Observation Fields
            - `id` (string) - Observation ID
            - `type` (string) - Observation type (SPAN, GENERATION, EVENT)
            - `name` (string) - Observation name
            - `traceId` (string) - Associated trace ID
            - `startTime` (datetime) - Observation start time
            - `endTime` (datetime) - Observation end time
            - `environment` (string) - Environment tag
            - `level` (string) - Log level (DEBUG, DEFAULT, WARNING, ERROR)
            - `statusMessage` (string) - Status message
            - `version` (string) - Version tag
            - `userId` (string) - User ID
            - `sessionId` (string) - Session ID

            ### Trace-Related Fields
            - `traceName` (string) - Name of the parent trace
            - `traceTags` (arrayOptions) - Tags from the parent trace
            - `tags` (arrayOptions) - Alias for traceTags

            ### Performance Metrics
            - `latency` (number) - Latency in seconds (calculated: end_time - start_time)
            - `timeToFirstToken` (number) - Time to first token in seconds
            - `tokensPerSecond` (number) - Output tokens per second

            ### Token Usage
            - `inputTokens` (number) - Number of input tokens
            - `outputTokens` (number) - Number of output tokens
            - `totalTokens` (number) - Total tokens (alias: `tokens`)

            ### Cost Metrics
            - `inputCost` (number) - Input cost in USD
            - `outputCost` (number) - Output cost in USD
            - `totalCost` (number) - Total cost in USD

            ### Model Information
            - `model` (string) - Provided model name (alias: `providedModelName`)
            - `promptName` (string) - Associated prompt name
            - `promptVersion` (number) - Associated prompt version

            ### Structured Data
            - `metadata` (stringObject/numberObject/categoryOptions) - Metadata key-value pairs. Use `key` parameter to filter on specific metadata keys.

            ## Filter Examples
            ```json
            [
              {
                "type": "string",
                "column": "type",
                "operator": "=",
                "value": "GENERATION"
              },
              {
                "type": "number",
                "column": "latency",
                "operator": ">=",
                "value": 2.5
              },
              {
                "type": "stringObject",
                "column": "metadata",
                "key": "environment",
                "operator": "=",
                "value": "production"
              }
            ]
            ```

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ObservationsV2Response]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/public/v2/observations",
            method="GET",
            params={
                "fields": fields,
                "expandMetadata": expand_metadata,
                "limit": limit,
                "cursor": cursor,
                "parseIoAsJson": parse_io_as_json,
                "name": name,
                "userId": user_id,
                "type": type,
                "traceId": trace_id,
                "level": level,
                "parentObservationId": parent_observation_id,
                "environment": environment,
                "fromStartTime": serialize_datetime(from_start_time)
                if from_start_time is not None
                else None,
                "toStartTime": serialize_datetime(to_start_time)
                if to_start_time is not None
                else None,
                "version": version,
                "filter": filter,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ObservationsV2Response,
                    parse_obj_as(
                        type_=ObservationsV2Response,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise Error(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 403:
                raise AccessDeniedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(
                status_code=_response.status_code,
                headers=dict(_response.headers),
                body=_response.text,
            )
        raise ApiError(
            status_code=_response.status_code,
            headers=dict(_response.headers),
            body=_response_json,
        )
