# 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.unprocessable_entity_error import UnprocessableEntityError
from ....types.delete_env_var_response import DeleteEnvVarResponse
from ....types.deployed_secrets_response import DeployedSecretsResponse
from ....types.env_var_list_response import EnvVarListResponse
from ....types.env_var_value import EnvVarValue
from ....types.http_validation_error import HttpValidationError
from ....types.set_env_var_response import SetEnvVarResponse

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


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

    def list(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        include_values: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[EnvVarListResponse]:
        """
        List PENDING secrets for an environment (from EnvVar table).

            This is what will be used on next deploy.
            For deployed state, use GET /agents/{namespace_slug}/{agent_name}/environments/{env}/secrets/deployed

            Note: is_secret=True values are NEVER returned, only non-secrets when include_values=True.

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

        agent_name : str

        env_name : str

        include_values : typing.Optional[bool]
            Include values for non-secrets (is_secret=False only)

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

        Returns
        -------
        HttpResponse[EnvVarListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/environments/{jsonable_encoder(env_name)}/secrets",
            method="GET",
            params={
                "include_values": include_values,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EnvVarListResponse,
                    parse_obj_as(
                        type_=EnvVarListResponse,  # 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 set(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        secrets: typing.Dict[str, EnvVarValue],
        redeploy: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SetEnvVarResponse]:
        """
        Set one or more secrets/config values.

            If redeploy=True (default) and environment has active deployment,
            triggers redeploy with same image but new secrets_snapshot.

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

        agent_name : str

        env_name : str

        secrets : typing.Dict[str, EnvVarValue]
            Dict of {key: {value, is_secret}} to set

        redeploy : typing.Optional[bool]
            If true and env has active deployment, trigger redeploy with new secrets

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

        Returns
        -------
        HttpResponse[SetEnvVarResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/environments/{jsonable_encoder(env_name)}/secrets",
            method="PUT",
            json={
                "redeploy": redeploy,
                "secrets": convert_and_respect_annotation_metadata(
                    object_=secrets, annotation=typing.Dict[str, EnvVarValue], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SetEnvVarResponse,
                    parse_obj_as(
                        type_=SetEnvVarResponse,  # 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_deployed(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[DeployedSecretsResponse]:
        """
        List DEPLOYED secrets for an environment (from Version.secrets_snapshot).

            This is what's currently running. May differ from pending state after rollback.
            Only returns keys, never actual values.

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

        agent_name : str

        env_name : str

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

        Returns
        -------
        HttpResponse[DeployedSecretsResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/environments/{jsonable_encoder(env_name)}/secrets/deployed",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DeployedSecretsResponse,
                    parse_obj_as(
                        type_=DeployedSecretsResponse,  # 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 delete(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        key: str,
        *,
        redeploy: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[DeleteEnvVarResponse]:
        """
        Delete a secret from an environment.

            If redeploy=True (default), triggers redeploy with updated secrets.

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

        agent_name : str

        env_name : str

        key : str

        redeploy : typing.Optional[bool]
            If true, trigger redeploy after deletion

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

        Returns
        -------
        HttpResponse[DeleteEnvVarResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(namespace_slug)}/{jsonable_encoder(agent_name)}/environments/{jsonable_encoder(env_name)}/secrets/{jsonable_encoder(key)}",
            method="DELETE",
            params={
                "redeploy": redeploy,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DeleteEnvVarResponse,
                    parse_obj_as(
                        type_=DeleteEnvVarResponse,  # 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 AsyncRawSecretsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        include_values: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[EnvVarListResponse]:
        """
        List PENDING secrets for an environment (from EnvVar table).

            This is what will be used on next deploy.
            For deployed state, use GET /agents/{namespace_slug}/{agent_name}/environments/{env}/secrets/deployed

            Note: is_secret=True values are NEVER returned, only non-secrets when include_values=True.

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

        agent_name : str

        env_name : str

        include_values : typing.Optional[bool]
            Include values for non-secrets (is_secret=False only)

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

        Returns
        -------
        AsyncHttpResponse[EnvVarListResponse]
            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)}/secrets",
            method="GET",
            params={
                "include_values": include_values,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    EnvVarListResponse,
                    parse_obj_as(
                        type_=EnvVarListResponse,  # 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 set(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        secrets: typing.Dict[str, EnvVarValue],
        redeploy: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[SetEnvVarResponse]:
        """
        Set one or more secrets/config values.

            If redeploy=True (default) and environment has active deployment,
            triggers redeploy with same image but new secrets_snapshot.

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

        agent_name : str

        env_name : str

        secrets : typing.Dict[str, EnvVarValue]
            Dict of {key: {value, is_secret}} to set

        redeploy : typing.Optional[bool]
            If true and env has active deployment, trigger redeploy with new secrets

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

        Returns
        -------
        AsyncHttpResponse[SetEnvVarResponse]
            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)}/secrets",
            method="PUT",
            json={
                "redeploy": redeploy,
                "secrets": convert_and_respect_annotation_metadata(
                    object_=secrets, annotation=typing.Dict[str, EnvVarValue], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    SetEnvVarResponse,
                    parse_obj_as(
                        type_=SetEnvVarResponse,  # 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_deployed(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        *,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[DeployedSecretsResponse]:
        """
        List DEPLOYED secrets for an environment (from Version.secrets_snapshot).

            This is what's currently running. May differ from pending state after rollback.
            Only returns keys, never actual values.

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

        agent_name : str

        env_name : str

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

        Returns
        -------
        AsyncHttpResponse[DeployedSecretsResponse]
            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)}/secrets/deployed",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DeployedSecretsResponse,
                    parse_obj_as(
                        type_=DeployedSecretsResponse,  # 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 delete(
        self,
        namespace_slug: str,
        agent_name: str,
        env_name: str,
        key: str,
        *,
        redeploy: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[DeleteEnvVarResponse]:
        """
        Delete a secret from an environment.

            If redeploy=True (default), triggers redeploy with updated secrets.

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

        agent_name : str

        env_name : str

        key : str

        redeploy : typing.Optional[bool]
            If true, trigger redeploy after deletion

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

        Returns
        -------
        AsyncHttpResponse[DeleteEnvVarResponse]
            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)}/secrets/{jsonable_encoder(key)}",
            method="DELETE",
            params={
                "redeploy": redeploy,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DeleteEnvVarResponse,
                    parse_obj_as(
                        type_=DeleteEnvVarResponse,  # 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)
