# 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 ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.build_prepare_response import BuildPrepareResponse
from ..types.build_status_response import BuildStatusResponse
from ..types.build_submit_response import BuildSubmitResponse
from ..types.http_validation_error import HttpValidationError

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


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

    def prepare(
        self, *, agent_name: str, namespace: str, tag: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BuildPrepareResponse]:
        """
        Return a presigned URL for uploading a build context archive to GCS.

        Parameters
        ----------
        agent_name : str
            Agent short name (without namespace prefix)

        namespace : str
            Target namespace slug for the build

        tag : str
            Image tag to build/push (typically git hash)

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

        Returns
        -------
        HttpResponse[BuildPrepareResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "builds/prepare",
            method="POST",
            json={
                "agent_name": agent_name,
                "namespace": namespace,
                "tag": tag,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BuildPrepareResponse,
                    parse_obj_as(
                        type_=BuildPrepareResponse,  # 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 submit(
        self,
        *,
        agent_name: str,
        bucket: str,
        namespace: str,
        object_key: str,
        tag: str,
        git_branch: typing.Optional[str] = OMIT,
        git_hash: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BuildSubmitResponse]:
        """
        Submit a Cloud Build build for an uploaded build context archive.

        Parameters
        ----------
        agent_name : str
            Agent short name

        bucket : str
            GCS bucket containing uploaded build context archive.

        namespace : str
            Target namespace slug

        object_key : str
            GCS object key for the uploaded build context archive.

        tag : str
            Image tag to build/push

        git_branch : typing.Optional[str]
            Optional git branch name for metadata.

        git_hash : typing.Optional[str]
            Optional git hash for metadata.

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

        Returns
        -------
        HttpResponse[BuildSubmitResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "builds/submit",
            method="POST",
            json={
                "agent_name": agent_name,
                "bucket": bucket,
                "git_branch": git_branch,
                "git_hash": git_hash,
                "namespace": namespace,
                "object_key": object_key,
                "tag": tag,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BuildSubmitResponse,
                    parse_obj_as(
                        type_=BuildSubmitResponse,  # 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, build_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BuildStatusResponse]:
        """
        Get build status for a Cloud Build build ID (proxied).

        Parameters
        ----------
        build_id : str

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

        Returns
        -------
        HttpResponse[BuildStatusResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"builds/{jsonable_encoder(build_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BuildStatusResponse,
                    parse_obj_as(
                        type_=BuildStatusResponse,  # 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 AsyncRawBuildsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def prepare(
        self, *, agent_name: str, namespace: str, tag: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BuildPrepareResponse]:
        """
        Return a presigned URL for uploading a build context archive to GCS.

        Parameters
        ----------
        agent_name : str
            Agent short name (without namespace prefix)

        namespace : str
            Target namespace slug for the build

        tag : str
            Image tag to build/push (typically git hash)

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

        Returns
        -------
        AsyncHttpResponse[BuildPrepareResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "builds/prepare",
            method="POST",
            json={
                "agent_name": agent_name,
                "namespace": namespace,
                "tag": tag,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BuildPrepareResponse,
                    parse_obj_as(
                        type_=BuildPrepareResponse,  # 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 submit(
        self,
        *,
        agent_name: str,
        bucket: str,
        namespace: str,
        object_key: str,
        tag: str,
        git_branch: typing.Optional[str] = OMIT,
        git_hash: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BuildSubmitResponse]:
        """
        Submit a Cloud Build build for an uploaded build context archive.

        Parameters
        ----------
        agent_name : str
            Agent short name

        bucket : str
            GCS bucket containing uploaded build context archive.

        namespace : str
            Target namespace slug

        object_key : str
            GCS object key for the uploaded build context archive.

        tag : str
            Image tag to build/push

        git_branch : typing.Optional[str]
            Optional git branch name for metadata.

        git_hash : typing.Optional[str]
            Optional git hash for metadata.

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

        Returns
        -------
        AsyncHttpResponse[BuildSubmitResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "builds/submit",
            method="POST",
            json={
                "agent_name": agent_name,
                "bucket": bucket,
                "git_branch": git_branch,
                "git_hash": git_hash,
                "namespace": namespace,
                "object_key": object_key,
                "tag": tag,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BuildSubmitResponse,
                    parse_obj_as(
                        type_=BuildSubmitResponse,  # 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, build_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BuildStatusResponse]:
        """
        Get build status for a Cloud Build build ID (proxied).

        Parameters
        ----------
        build_id : str

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

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