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

from __future__ import annotations

import typing

from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from ..types.branch_response import BranchResponse
from ..types.redeploy_response import RedeployResponse
from ..types.rollback_response import RollbackResponse
from .raw_client import AsyncRawBranchesClient, RawBranchesClient

if typing.TYPE_CHECKING:
    from .events.client import AsyncEventsClient, EventsClient
    from .versions.client import AsyncVersionsClient, VersionsClient
# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class BranchesClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawBranchesClient(client_wrapper=client_wrapper)
        self._client_wrapper = client_wrapper
        self._events: typing.Optional[EventsClient] = None
        self._versions: typing.Optional[VersionsClient] = None

    @property
    def with_raw_response(self) -> RawBranchesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawBranchesClient
        """
        return self._raw_client

    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,
    ) -> 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
        -------
        RollbackResponse
            Successful Response

        Examples
        --------
        from terminaluse import TerminalUseBase

        client = TerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )
        client.branches.agents_environments_rollback_create(
            namespace_slug="namespace_slug",
            agent_name="agent_name",
            env_name="env_name",
        )
        """
        _response = self._raw_client.agents_environments_rollback_create(
            namespace_slug, agent_name, env_name, target_version_id=target_version_id, request_options=request_options
        )
        return _response.data

    def retrieve(self, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> 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
        -------
        BranchResponse
            Successful Response

        Examples
        --------
        from terminaluse import TerminalUseBase

        client = TerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )
        client.branches.retrieve(
            branch_id="branch_id",
        )
        """
        _response = self._raw_client.retrieve(branch_id, request_options=request_options)
        return _response.data

    def redeploy(self, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> 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
        -------
        RedeployResponse
            Successful Response

        Examples
        --------
        from terminaluse import TerminalUseBase

        client = TerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )
        client.branches.redeploy(
            branch_id="branch_id",
        )
        """
        _response = self._raw_client.redeploy(branch_id, request_options=request_options)
        return _response.data

    def rollback(
        self,
        branch_id: str,
        *,
        target_version_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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
        -------
        RollbackResponse
            Successful Response

        Examples
        --------
        from terminaluse import TerminalUseBase

        client = TerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )
        client.branches.rollback(
            branch_id="branch_id",
        )
        """
        _response = self._raw_client.rollback(
            branch_id, target_version_id=target_version_id, request_options=request_options
        )
        return _response.data

    @property
    def events(self):
        if self._events is None:
            from .events.client import EventsClient  # noqa: E402

            self._events = EventsClient(client_wrapper=self._client_wrapper)
        return self._events

    @property
    def versions(self):
        if self._versions is None:
            from .versions.client import VersionsClient  # noqa: E402

            self._versions = VersionsClient(client_wrapper=self._client_wrapper)
        return self._versions


class AsyncBranchesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawBranchesClient(client_wrapper=client_wrapper)
        self._client_wrapper = client_wrapper
        self._events: typing.Optional[AsyncEventsClient] = None
        self._versions: typing.Optional[AsyncVersionsClient] = None

    @property
    def with_raw_response(self) -> AsyncRawBranchesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawBranchesClient
        """
        return self._raw_client

    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,
    ) -> 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
        -------
        RollbackResponse
            Successful Response

        Examples
        --------
        import asyncio

        from terminaluse import AsyncTerminalUseBase

        client = AsyncTerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.branches.agents_environments_rollback_create(
                namespace_slug="namespace_slug",
                agent_name="agent_name",
                env_name="env_name",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.agents_environments_rollback_create(
            namespace_slug, agent_name, env_name, target_version_id=target_version_id, request_options=request_options
        )
        return _response.data

    async def retrieve(
        self, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> 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
        -------
        BranchResponse
            Successful Response

        Examples
        --------
        import asyncio

        from terminaluse import AsyncTerminalUseBase

        client = AsyncTerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.branches.retrieve(
                branch_id="branch_id",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.retrieve(branch_id, request_options=request_options)
        return _response.data

    async def redeploy(
        self, branch_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> 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
        -------
        RedeployResponse
            Successful Response

        Examples
        --------
        import asyncio

        from terminaluse import AsyncTerminalUseBase

        client = AsyncTerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.branches.redeploy(
                branch_id="branch_id",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.redeploy(branch_id, request_options=request_options)
        return _response.data

    async def rollback(
        self,
        branch_id: str,
        *,
        target_version_id: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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
        -------
        RollbackResponse
            Successful Response

        Examples
        --------
        import asyncio

        from terminaluse import AsyncTerminalUseBase

        client = AsyncTerminalUseBase(
            agent_api_key="YOUR_AGENT_API_KEY",
            token="YOUR_TOKEN",
            base_url="https://yourhost.com/path/to/api",
        )


        async def main() -> None:
            await client.branches.rollback(
                branch_id="branch_id",
            )


        asyncio.run(main())
        """
        _response = await self._raw_client.rollback(
            branch_id, target_version_id=target_version_id, request_options=request_options
        )
        return _response.data

    @property
    def events(self):
        if self._events is None:
            from .events.client import AsyncEventsClient  # noqa: E402

            self._events = AsyncEventsClient(client_wrapper=self._client_wrapper)
        return self._events

    @property
    def versions(self):
        if self._versions is None:
            from .versions.client import AsyncVersionsClient  # noqa: E402

            self._versions = AsyncVersionsClient(client_wrapper=self._client_wrapper)
        return self._versions
