# 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_list_response import BranchListResponse
from ...types.branch_response import BranchResponse
from ...types.http_validation_error import HttpValidationError
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 retrieve(
        self,
        namespace_slug: str,
        agent_name: str,
        *,
        branch: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BranchResponse]:
        """
        Get a specific branch by agent name and git branch.

            The git branch name will be normalized (lowercased, slashes converted to hyphens).
            For example, "feature/new-tool" becomes "feature-new-tool".

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

        agent_name : str

        branch : str
            Target branch (e.g., 'main', 'feature/login')

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

        Returns
        -------
        HttpResponse[BranchResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/branch",
            method="GET",
            params={
                "branch": branch,
            },
            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 list(
        self,
        namespace_slug: str,
        agent_name: str,
        *,
        include_retired: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BranchListResponse]:
        """
        List all branches for an agent.

            Each branch represents a git branch (e.g., main, staging, feature-x).
            By default, retired branches are excluded.

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

        agent_name : str

        include_retired : typing.Optional[bool]
            Include retired branches in results

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

        Returns
        -------
        HttpResponse[BranchListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/branches",
            method="GET",
            params={
                "include_retired": include_retired,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BranchListResponse,
                    parse_obj_as(
                        type_=BranchListResponse,  # 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,
        namespace_slug: str,
        agent_name: str,
        branch: 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 namespace, agent, and git branch name.

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

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

        agent_name : str

        branch : 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)}/branches/{jsonable_encoder(branch)}/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 retrieve(
        self,
        namespace_slug: str,
        agent_name: str,
        *,
        branch: str,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BranchResponse]:
        """
        Get a specific branch by agent name and git branch.

            The git branch name will be normalized (lowercased, slashes converted to hyphens).
            For example, "feature/new-tool" becomes "feature-new-tool".

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

        agent_name : str

        branch : str
            Target branch (e.g., 'main', 'feature/login')

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

        Returns
        -------
        AsyncHttpResponse[BranchResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/branch",
            method="GET",
            params={
                "branch": branch,
            },
            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 list(
        self,
        namespace_slug: str,
        agent_name: str,
        *,
        include_retired: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BranchListResponse]:
        """
        List all branches for an agent.

            Each branch represents a git branch (e.g., main, staging, feature-x).
            By default, retired branches are excluded.

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

        agent_name : str

        include_retired : typing.Optional[bool]
            Include retired branches in results

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

        Returns
        -------
        AsyncHttpResponse[BranchListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/branches",
            method="GET",
            params={
                "include_retired": include_retired,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BranchListResponse,
                    parse_obj_as(
                        type_=BranchListResponse,  # 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,
        namespace_slug: str,
        agent_name: str,
        branch: 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 namespace, agent, and git branch name.

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

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

        agent_name : str

        branch : 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)}/branches/{jsonable_encoder(branch)}/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)
