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

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 ...core.serialization import convert_and_respect_annotation_metadata
from ...errors.bad_request_error import BadRequestError
from ...types.logs_filter_query import LogsFilterQuery
from ...types.logs_response import LogsResponse


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

    def get(
        self,
        pipeline_run_name: str,
        *,
        start_ts: typing.Optional[str] = None,
        end_ts: typing.Optional[str] = None,
        limit: typing.Optional[str] = None,
        direction: typing.Optional[str] = None,
        filter_query: typing.Optional[LogsFilterQuery] = None,
        num_logs_to_ignore: typing.Optional[float] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[LogsResponse]:
        """
        Get logs for a given pipeline run by its name, with optional filters and time range.

        Parameters
        ----------
        pipeline_run_name : str
            PipelineRun Name

        start_ts : typing.Optional[str]
            Start timestamp for querying logs, in nanoseconds from the Unix epoch.

        end_ts : typing.Optional[str]
            End timestamp for querying logs, in nanoseconds from the Unix epoch.

        limit : typing.Optional[str]
            Max number of log lines to fetch

        direction : typing.Optional[str]
            Direction of sorting logs. Can be `asc` or `desc`

        filter_query : typing.Optional[LogsFilterQuery]
            Query to filter logs

        num_logs_to_ignore : typing.Optional[float]
            Number of logs corresponding to the starting timestamp to be ignored.

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

        Returns
        -------
        HttpResponse[LogsResponse]
            Successfully retrieved build logs for the pipeline run
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/svc/v1/build-logs/{jsonable_encoder(pipeline_run_name)}",
            method="GET",
            params={
                "startTs": start_ts,
                "endTs": end_ts,
                "limit": limit,
                "direction": direction,
                "filterQuery": convert_and_respect_annotation_metadata(
                    object_=filter_query, annotation=LogsFilterQuery, direction="write"
                ),
                "numLogsToIgnore": num_logs_to_ignore,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    LogsResponse,
                    parse_obj_as(
                        type_=LogsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    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 AsyncRawBuildLogsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get(
        self,
        pipeline_run_name: str,
        *,
        start_ts: typing.Optional[str] = None,
        end_ts: typing.Optional[str] = None,
        limit: typing.Optional[str] = None,
        direction: typing.Optional[str] = None,
        filter_query: typing.Optional[LogsFilterQuery] = None,
        num_logs_to_ignore: typing.Optional[float] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[LogsResponse]:
        """
        Get logs for a given pipeline run by its name, with optional filters and time range.

        Parameters
        ----------
        pipeline_run_name : str
            PipelineRun Name

        start_ts : typing.Optional[str]
            Start timestamp for querying logs, in nanoseconds from the Unix epoch.

        end_ts : typing.Optional[str]
            End timestamp for querying logs, in nanoseconds from the Unix epoch.

        limit : typing.Optional[str]
            Max number of log lines to fetch

        direction : typing.Optional[str]
            Direction of sorting logs. Can be `asc` or `desc`

        filter_query : typing.Optional[LogsFilterQuery]
            Query to filter logs

        num_logs_to_ignore : typing.Optional[float]
            Number of logs corresponding to the starting timestamp to be ignored.

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

        Returns
        -------
        AsyncHttpResponse[LogsResponse]
            Successfully retrieved build logs for the pipeline run
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/svc/v1/build-logs/{jsonable_encoder(pipeline_run_name)}",
            method="GET",
            params={
                "startTs": start_ts,
                "endTs": end_ts,
                "limit": limit,
                "direction": direction,
                "filterQuery": convert_and_respect_annotation_metadata(
                    object_=filter_query, annotation=LogsFilterQuery, direction="write"
                ),
                "numLogsToIgnore": num_logs_to_ignore,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    LogsResponse,
                    parse_obj_as(
                        type_=LogsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    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)
