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

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

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
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 ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from ..types.span import Span

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


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

    def list(
        self,
        *,
        task_id: str,
        trace_id: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        order_by: typing.Optional[str] = None,
        order_direction: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.List[Span]]:
        """
        List all spans for a given task.
        Requires read permission on the task.
        Optionally filter by trace_id within the task.

        Parameters
        ----------
        task_id : str
            The task ID

        trace_id : typing.Optional[str]

        limit : typing.Optional[int]

        page_number : typing.Optional[int]

        order_by : typing.Optional[str]

        order_direction : typing.Optional[str]

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

        Returns
        -------
        HttpResponse[typing.List[Span]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "spans",
            method="GET",
            params={
                "trace_id": trace_id,
                "limit": limit,
                "page_number": page_number,
                "order_by": order_by,
                "order_direction": order_direction,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[Span],
                    parse_obj_as(
                        type_=typing.List[Span],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 create(
        self,
        *,
        name: str,
        start_time: dt.datetime,
        task_id: str,
        trace_id: str,
        data: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        end_time: typing.Optional[dt.datetime] = OMIT,
        id: typing.Optional[str] = OMIT,
        input: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        output: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        parent_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Span]:
        """
        Create a new span with the provided parameters.
        Requires update (edit) permission on the associated task.

        Parameters
        ----------
        name : str
            Name that describes what operation this span represents

        start_time : dt.datetime
            The time the span started

        task_id : str
            ID of the task this span is associated with, used for authorization

        trace_id : str
            Unique identifier for the trace this span belongs to

        data : typing.Optional[typing.Dict[str, typing.Any]]
            Any additional metadata or context for the span

        end_time : typing.Optional[dt.datetime]
            The time the span ended

        id : typing.Optional[str]
            Unique identifier for the span. If not provided, an ID will be generated.

        input : typing.Optional[typing.Dict[str, typing.Any]]
            Input parameters or data for the operation

        output : typing.Optional[typing.Dict[str, typing.Any]]
            Output data resulting from the operation

        parent_id : typing.Optional[str]
            ID of the parent span if this is a child span in a trace

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

        Returns
        -------
        HttpResponse[Span]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "spans",
            method="POST",
            json={
                "data": data,
                "end_time": end_time,
                "id": id,
                "input": input,
                "name": name,
                "output": output,
                "parent_id": parent_id,
                "start_time": start_time,
                "task_id": task_id,
                "trace_id": trace_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Span,
                    parse_obj_as(
                        type_=Span,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 retrieve(self, span_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[Span]:
        """
        Get a span by ID.
        Requires read permission on the span's parent task.

        Parameters
        ----------
        span_id : str

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

        Returns
        -------
        HttpResponse[Span]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"spans/{jsonable_encoder(span_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Span,
                    parse_obj_as(
                        type_=Span,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 update(
        self,
        span_id: str,
        *,
        data: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        end_time: typing.Optional[dt.datetime] = OMIT,
        input: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        name: typing.Optional[str] = OMIT,
        output: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        parent_id: typing.Optional[str] = OMIT,
        start_time: typing.Optional[dt.datetime] = OMIT,
        trace_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Span]:
        """
        Update a span with the provided output data and mark it as complete.
        Requires update (edit) permission on the span's parent task.

        Parameters
        ----------
        span_id : str

        data : typing.Optional[typing.Dict[str, typing.Any]]
            Any additional metadata or context for the span

        end_time : typing.Optional[dt.datetime]
            The time the span ended

        input : typing.Optional[typing.Dict[str, typing.Any]]
            Input parameters or data for the operation

        name : typing.Optional[str]
            Name that describes what operation this span represents

        output : typing.Optional[typing.Dict[str, typing.Any]]
            Output data resulting from the operation

        parent_id : typing.Optional[str]
            ID of the parent span if this is a child span in a trace

        start_time : typing.Optional[dt.datetime]
            The time the span started

        trace_id : typing.Optional[str]
            Unique identifier for the trace this span belongs to

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

        Returns
        -------
        HttpResponse[Span]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"spans/{jsonable_encoder(span_id)}",
            method="PATCH",
            json={
                "data": data,
                "end_time": end_time,
                "input": input,
                "name": name,
                "output": output,
                "parent_id": parent_id,
                "start_time": start_time,
                "trace_id": trace_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Span,
                    parse_obj_as(
                        type_=Span,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 AsyncRawSpansClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        task_id: str,
        trace_id: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        page_number: typing.Optional[int] = None,
        order_by: typing.Optional[str] = None,
        order_direction: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.List[Span]]:
        """
        List all spans for a given task.
        Requires read permission on the task.
        Optionally filter by trace_id within the task.

        Parameters
        ----------
        task_id : str
            The task ID

        trace_id : typing.Optional[str]

        limit : typing.Optional[int]

        page_number : typing.Optional[int]

        order_by : typing.Optional[str]

        order_direction : typing.Optional[str]

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

        Returns
        -------
        AsyncHttpResponse[typing.List[Span]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "spans",
            method="GET",
            params={
                "trace_id": trace_id,
                "limit": limit,
                "page_number": page_number,
                "order_by": order_by,
                "order_direction": order_direction,
                "task_id": task_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[Span],
                    parse_obj_as(
                        type_=typing.List[Span],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 create(
        self,
        *,
        name: str,
        start_time: dt.datetime,
        task_id: str,
        trace_id: str,
        data: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        end_time: typing.Optional[dt.datetime] = OMIT,
        id: typing.Optional[str] = OMIT,
        input: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        output: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        parent_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Span]:
        """
        Create a new span with the provided parameters.
        Requires update (edit) permission on the associated task.

        Parameters
        ----------
        name : str
            Name that describes what operation this span represents

        start_time : dt.datetime
            The time the span started

        task_id : str
            ID of the task this span is associated with, used for authorization

        trace_id : str
            Unique identifier for the trace this span belongs to

        data : typing.Optional[typing.Dict[str, typing.Any]]
            Any additional metadata or context for the span

        end_time : typing.Optional[dt.datetime]
            The time the span ended

        id : typing.Optional[str]
            Unique identifier for the span. If not provided, an ID will be generated.

        input : typing.Optional[typing.Dict[str, typing.Any]]
            Input parameters or data for the operation

        output : typing.Optional[typing.Dict[str, typing.Any]]
            Output data resulting from the operation

        parent_id : typing.Optional[str]
            ID of the parent span if this is a child span in a trace

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

        Returns
        -------
        AsyncHttpResponse[Span]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "spans",
            method="POST",
            json={
                "data": data,
                "end_time": end_time,
                "id": id,
                "input": input,
                "name": name,
                "output": output,
                "parent_id": parent_id,
                "start_time": start_time,
                "task_id": task_id,
                "trace_id": trace_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Span,
                    parse_obj_as(
                        type_=Span,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 retrieve(
        self, span_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[Span]:
        """
        Get a span by ID.
        Requires read permission on the span's parent task.

        Parameters
        ----------
        span_id : str

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

        Returns
        -------
        AsyncHttpResponse[Span]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"spans/{jsonable_encoder(span_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Span,
                    parse_obj_as(
                        type_=Span,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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 update(
        self,
        span_id: str,
        *,
        data: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        end_time: typing.Optional[dt.datetime] = OMIT,
        input: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        name: typing.Optional[str] = OMIT,
        output: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        parent_id: typing.Optional[str] = OMIT,
        start_time: typing.Optional[dt.datetime] = OMIT,
        trace_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Span]:
        """
        Update a span with the provided output data and mark it as complete.
        Requires update (edit) permission on the span's parent task.

        Parameters
        ----------
        span_id : str

        data : typing.Optional[typing.Dict[str, typing.Any]]
            Any additional metadata or context for the span

        end_time : typing.Optional[dt.datetime]
            The time the span ended

        input : typing.Optional[typing.Dict[str, typing.Any]]
            Input parameters or data for the operation

        name : typing.Optional[str]
            Name that describes what operation this span represents

        output : typing.Optional[typing.Dict[str, typing.Any]]
            Output data resulting from the operation

        parent_id : typing.Optional[str]
            ID of the parent span if this is a child span in a trace

        start_time : typing.Optional[dt.datetime]
            The time the span started

        trace_id : typing.Optional[str]
            Unique identifier for the trace this span belongs to

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

        Returns
        -------
        AsyncHttpResponse[Span]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"spans/{jsonable_encoder(span_id)}",
            method="PATCH",
            json={
                "data": data,
                "end_time": end_time,
                "input": input,
                "name": name,
                "output": output,
                "parent_id": parent_id,
                "start_time": start_time,
                "trace_id": trace_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Span,
                    parse_obj_as(
                        type_=Span,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        parse_obj_as(
                            type_=HttpValidationError,  # 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)
