# 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.pagination import AsyncPager, SyncPager
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.conflict_error import ConflictError
from ..errors.not_found_error import NotFoundError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.environment import Environment
from ..types.environment_manifest import EnvironmentManifest
from ..types.get_environment_response import GetEnvironmentResponse
from ..types.http_error import HttpError
from ..types.list_environments_response import ListEnvironmentsResponse

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


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

    def list(
        self,
        *,
        limit: typing.Optional[int] = 100,
        offset: typing.Optional[int] = 0,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[Environment, ListEnvironmentsResponse]:
        """
        List environments, if no environments are found, default environments are created and returned. Pagination is available based on query parameters

        Parameters
        ----------
        limit : typing.Optional[int]
            Number of items per page

        offset : typing.Optional[int]
            Number of items to skip

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

        Returns
        -------
        SyncPager[Environment, ListEnvironmentsResponse]
            Returns a list of environment. If pagination parameters are provided, the response includes paginated data
        """
        offset = offset if offset is not None else 0

        _response = self._client_wrapper.httpx_client.request(
            "api/svc/v1/environments",
            method="GET",
            params={
                "limit": limit,
                "offset": offset,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListEnvironmentsResponse,
                    parse_obj_as(
                        type_=ListEnvironmentsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _has_next = True
                _get_next = lambda: self.list(
                    limit=limit,
                    offset=offset + len(_items),
                    request_options=request_options,
                )
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            _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 create_or_update(
        self,
        *,
        manifest: EnvironmentManifest,
        dry_run: typing.Optional[bool] = False,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetEnvironmentResponse]:
        """
        Creates a new Environment or updates an existing Environment.

        Parameters
        ----------
        manifest : EnvironmentManifest
            Environment Manifest

        dry_run : typing.Optional[bool]
            Dry run

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

        Returns
        -------
        HttpResponse[GetEnvironmentResponse]
            Returns the created or updated Environment
        """
        _response = self._client_wrapper.httpx_client.request(
            "api/svc/v1/environments",
            method="PUT",
            json={
                "manifest": convert_and_respect_annotation_metadata(
                    object_=manifest, annotation=EnvironmentManifest, direction="write"
                ),
                "dryRun": dry_run,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetEnvironmentResponse,
                    parse_obj_as(
                        type_=GetEnvironmentResponse,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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 get(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetEnvironmentResponse]:
        """
        Get Environment associated with the provided id.

        Parameters
        ----------
        id : str
            Environment id

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

        Returns
        -------
        HttpResponse[GetEnvironmentResponse]
            Returns the Environment associated with the provided id
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/svc/v1/environments/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetEnvironmentResponse,
                    parse_obj_as(
                        type_=GetEnvironmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _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, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[bool]:
        """
        Delete Environment associated with the provided id.

        Parameters
        ----------
        id : str
            Environment id

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

        Returns
        -------
        HttpResponse[bool]
            Returns true if the Environment is deleted successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            f"api/svc/v1/environments/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    bool,
                    parse_obj_as(
                        type_=bool,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpError,
                        parse_obj_as(
                            type_=HttpError,  # 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 AsyncRawEnvironmentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list(
        self,
        *,
        limit: typing.Optional[int] = 100,
        offset: typing.Optional[int] = 0,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[Environment, ListEnvironmentsResponse]:
        """
        List environments, if no environments are found, default environments are created and returned. Pagination is available based on query parameters

        Parameters
        ----------
        limit : typing.Optional[int]
            Number of items per page

        offset : typing.Optional[int]
            Number of items to skip

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

        Returns
        -------
        AsyncPager[Environment, ListEnvironmentsResponse]
            Returns a list of environment. If pagination parameters are provided, the response includes paginated data
        """
        offset = offset if offset is not None else 0

        _response = await self._client_wrapper.httpx_client.request(
            "api/svc/v1/environments",
            method="GET",
            params={
                "limit": limit,
                "offset": offset,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListEnvironmentsResponse,
                    parse_obj_as(
                        type_=ListEnvironmentsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _items = _parsed_response.data
                _has_next = True

                async def _get_next():
                    return await self.list(
                        limit=limit,
                        offset=offset + len(_items),
                        request_options=request_options,
                    )

                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response)
            _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 create_or_update(
        self,
        *,
        manifest: EnvironmentManifest,
        dry_run: typing.Optional[bool] = False,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetEnvironmentResponse]:
        """
        Creates a new Environment or updates an existing Environment.

        Parameters
        ----------
        manifest : EnvironmentManifest
            Environment Manifest

        dry_run : typing.Optional[bool]
            Dry run

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

        Returns
        -------
        AsyncHttpResponse[GetEnvironmentResponse]
            Returns the created or updated Environment
        """
        _response = await self._client_wrapper.httpx_client.request(
            "api/svc/v1/environments",
            method="PUT",
            json={
                "manifest": convert_and_respect_annotation_metadata(
                    object_=manifest, annotation=EnvironmentManifest, direction="write"
                ),
                "dryRun": dry_run,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetEnvironmentResponse,
                    parse_obj_as(
                        type_=GetEnvironmentResponse,  # 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(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # 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 get(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetEnvironmentResponse]:
        """
        Get Environment associated with the provided id.

        Parameters
        ----------
        id : str
            Environment id

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

        Returns
        -------
        AsyncHttpResponse[GetEnvironmentResponse]
            Returns the Environment associated with the provided id
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/svc/v1/environments/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetEnvironmentResponse,
                    parse_obj_as(
                        type_=GetEnvironmentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _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, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[bool]:
        """
        Delete Environment associated with the provided id.

        Parameters
        ----------
        id : str
            Environment id

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

        Returns
        -------
        AsyncHttpResponse[bool]
            Returns true if the Environment is deleted successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"api/svc/v1/environments/{jsonable_encoder(id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    bool,
                    parse_obj_as(
                        type_=bool,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 409:
                raise ConflictError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpError,
                        parse_obj_as(
                            type_=HttpError,  # 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)
