# 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.branch_response import BranchResponse
from ..types.http_validation_error import HttpValidationError
from ..types.redeploy_response import RedeployResponse
from ..types.rollback_response import RollbackResponse

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


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

    def agents_environments_rollback_create(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        target_version_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[RollbackResponse]:
        """
        Roll back an environment to a previous version.

            Resolves environment to branch via branch rules.
            Only works for environments with a single, literal branch rule (no wildcards).

            Key behavior:
            - EnvVar table is NOT modified (remains pending state for next deploy)
            - Uses Version.secrets_snapshot as deployed state

        Parameters
        ----------
        namespace_slug : str

        agent_name : str

        env_name : str

        target_version_id : typing.Optional[str]
            Version ID to rollback to (defaults to previous version if not specified)

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

        Returns
        -------
        HttpResponse[RollbackResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/environments/{jsonable_encoder(env_name)}/rollback",
            method="POST",
            json={
                "target_version_id": target_version_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    RollbackResponse,
                    parse_obj_as(
                        type_=RollbackResponse,  # 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, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[BranchResponse]:
        """
        Get branch details by ID.

            Used by CLI to poll for branch status after calling POST /agents/deploy.
            Poll until status is READY (success) or FAILED/TIMEOUT (failure).

        Parameters
        ----------
        branch_id : str

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

        Returns
        -------
        HttpResponse[BranchResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"branches/{jsonable_encoder(branch_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BranchResponse,
                    parse_obj_as(
                        type_=BranchResponse,  # 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 redeploy(
        self, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[RedeployResponse]:
        """
        Redeploy a branch with the current secrets from the EnvVar table.

            Creates a new Version with:
            - Same image as current version
            - Fresh secrets_snapshot from current EnvVars

            Use this after updating secrets to apply them to a running branch.

        Parameters
        ----------
        branch_id : str

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

        Returns
        -------
        HttpResponse[RedeployResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"branches/{jsonable_encoder(branch_id)}/redeploy",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    RedeployResponse,
                    parse_obj_as(
                        type_=RedeployResponse,  # 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 rollback(
        self,
        branch_id: str,
        *,
        target_version_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[RollbackResponse]:
        """
        Roll back a branch to a previous version by branch ID.

            Key behavior:
            - EnvVar table is NOT modified (remains pending state)
            - Uses Version.secrets_snapshot as deployed state

        Parameters
        ----------
        branch_id : str

        target_version_id : typing.Optional[str]
            Version ID to rollback to (defaults to previous version if not specified)

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

        Returns
        -------
        HttpResponse[RollbackResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"branches/{jsonable_encoder(branch_id)}/rollback",
            method="POST",
            json={
                "target_version_id": target_version_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    RollbackResponse,
                    parse_obj_as(
                        type_=RollbackResponse,  # 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 AsyncRawBranchesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def agents_environments_rollback_create(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        target_version_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[RollbackResponse]:
        """
        Roll back an environment to a previous version.

            Resolves environment to branch via branch rules.
            Only works for environments with a single, literal branch rule (no wildcards).

            Key behavior:
            - EnvVar table is NOT modified (remains pending state for next deploy)
            - Uses Version.secrets_snapshot as deployed state

        Parameters
        ----------
        namespace_slug : str

        agent_name : str

        env_name : str

        target_version_id : typing.Optional[str]
            Version ID to rollback to (defaults to previous version if not specified)

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

        Returns
        -------
        AsyncHttpResponse[RollbackResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/environments/{jsonable_encoder(env_name)}/rollback",
            method="POST",
            json={
                "target_version_id": target_version_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    RollbackResponse,
                    parse_obj_as(
                        type_=RollbackResponse,  # 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, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[BranchResponse]:
        """
        Get branch details by ID.

            Used by CLI to poll for branch status after calling POST /agents/deploy.
            Poll until status is READY (success) or FAILED/TIMEOUT (failure).

        Parameters
        ----------
        branch_id : str

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

        Returns
        -------
        AsyncHttpResponse[BranchResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"branches/{jsonable_encoder(branch_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BranchResponse,
                    parse_obj_as(
                        type_=BranchResponse,  # 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 redeploy(
        self, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[RedeployResponse]:
        """
        Redeploy a branch with the current secrets from the EnvVar table.

            Creates a new Version with:
            - Same image as current version
            - Fresh secrets_snapshot from current EnvVars

            Use this after updating secrets to apply them to a running branch.

        Parameters
        ----------
        branch_id : str

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

        Returns
        -------
        AsyncHttpResponse[RedeployResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"branches/{jsonable_encoder(branch_id)}/redeploy",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    RedeployResponse,
                    parse_obj_as(
                        type_=RedeployResponse,  # 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 rollback(
        self,
        branch_id: str,
        *,
        target_version_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[RollbackResponse]:
        """
        Roll back a branch to a previous version by branch ID.

            Key behavior:
            - EnvVar table is NOT modified (remains pending state)
            - Uses Version.secrets_snapshot as deployed state

        Parameters
        ----------
        branch_id : str

        target_version_id : typing.Optional[str]
            Version ID to rollback to (defaults to previous version if not specified)

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

        Returns
        -------
        AsyncHttpResponse[RollbackResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"branches/{jsonable_encoder(branch_id)}/rollback",
            method="POST",
            json={
                "target_version_id": target_version_id,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    RollbackResponse,
                    parse_obj_as(
                        type_=RollbackResponse,  # 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)
