# 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 ...commons.types.observations_view import ObservationsView
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.jsonable_encoder import jsonable_encoder
from ...core.pydantic_utilities import parse_obj_as
from ...core.request_options import RequestOptions
from .types.observations_views import ObservationsViews


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

    def get(
        self,
        observation_id: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ObservationsView]:
        """
        Get a observation

        Parameters
        ----------
        observation_id : str
            The unique langfuse identifier of an observation, can be an event, span or generation

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

        Returns
        -------
        HttpResponse[ObservationsView]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/public/observations/{jsonable_encoder(observation_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ObservationsView,
                    parse_obj_as(
                        type_=ObservationsView,  # 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,
        )

    def get_many(
        self,
        *,
        page: typing.Optional[int] = None,
        limit: typing.Optional[int] = 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[ObservationsViews]:
        """
        Get a list of observations.

        Consider using the [v2 observations endpoint](/api-reference#tag/observationsv2/GET/api/public/v2/observations) for cursor-based pagination and field selection.

        Parameters
        ----------
        page : typing.Optional[int]
            Page number, starts at 1.

        limit : typing.Optional[int]
            Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.

        name : typing.Optional[str]

        user_id : typing.Optional[str]

        type : typing.Optional[str]

        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

            ### 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
            - `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.

            ### Associated Trace Fields (requires join with traces table)
            - `userId` (string) - User ID from associated trace
            - `traceName` (string) - Name from associated trace
            - `traceEnvironment` (string) - Environment from associated trace
            - `traceTags` (arrayOptions) - Tags from associated trace

            ## 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[ObservationsViews]
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/public/observations",
            method="GET",
            params={
                "page": page,
                "limit": limit,
                "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(
                    ObservationsViews,
                    parse_obj_as(
                        type_=ObservationsViews,  # 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 AsyncRawObservationsV1Client:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get(
        self,
        observation_id: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ObservationsView]:
        """
        Get a observation

        Parameters
        ----------
        observation_id : str
            The unique langfuse identifier of an observation, can be an event, span or generation

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

        Returns
        -------
        AsyncHttpResponse[ObservationsView]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/public/observations/{jsonable_encoder(observation_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ObservationsView,
                    parse_obj_as(
                        type_=ObservationsView,  # 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,
        )

    async def get_many(
        self,
        *,
        page: typing.Optional[int] = None,
        limit: typing.Optional[int] = 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[ObservationsViews]:
        """
        Get a list of observations.

        Consider using the [v2 observations endpoint](/api-reference#tag/observationsv2/GET/api/public/v2/observations) for cursor-based pagination and field selection.

        Parameters
        ----------
        page : typing.Optional[int]
            Page number, starts at 1.

        limit : typing.Optional[int]
            Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.

        name : typing.Optional[str]

        user_id : typing.Optional[str]

        type : typing.Optional[str]

        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

            ### 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
            - `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.

            ### Associated Trace Fields (requires join with traces table)
            - `userId` (string) - User ID from associated trace
            - `traceName` (string) - Name from associated trace
            - `traceEnvironment` (string) - Environment from associated trace
            - `traceTags` (arrayOptions) - Tags from associated trace

            ## 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[ObservationsViews]
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/public/observations",
            method="GET",
            params={
                "page": page,
                "limit": limit,
                "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(
                    ObservationsViews,
                    parse_obj_as(
                        type_=ObservationsViews,  # 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,
        )
