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

import typing
from .environment import EarthEnvironment
import httpx
from .core.client_wrapper import SyncClientWrapper
from .weather.client import WeatherClient
import datetime as dt
from .types.timezone import Timezone
from .types.units import Units
from .core.request_options import RequestOptions
from .types.daily_weather_response import DailyWeatherResponse
from .core.datetime_utils import serialize_datetime
from .core.pydantic_utilities import parse_obj_as
from .errors.unprocessable_entity_error import UnprocessableEntityError
from .types.http_validation_error import HttpValidationError
from json.decoder import JSONDecodeError
from .core.api_error import ApiError
from .types.hourly_weather_response import HourlyWeatherResponse
from .core.client_wrapper import AsyncClientWrapper
from .weather.client import AsyncWeatherClient


class Earth:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.

    Parameters
    ----------
    base_url : typing.Optional[str]
        The base url to use for requests from the client.

    environment : EarthEnvironment
        The environment to use for requests from the client. from .environment import EarthEnvironment



        Defaults to EarthEnvironment.PRODUCTION



    api_key : str
    timeout : typing.Optional[float]
        The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.

    follow_redirects : typing.Optional[bool]
        Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.

    httpx_client : typing.Optional[httpx.Client]
        The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.

    Examples
    --------
    from silurian import Earth

    client = Earth(
        api_key="YOUR_API_KEY",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: EarthEnvironment = EarthEnvironment.PRODUCTION,
        api_key: str,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.Client] = None,
    ):
        _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
        self._client_wrapper = SyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            api_key=api_key,
            httpx_client=httpx_client
            if httpx_client is not None
            else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
            if follow_redirects is not None
            else httpx.Client(timeout=_defaulted_timeout),
            timeout=_defaulted_timeout,
        )
        self.weather = WeatherClient(client_wrapper=self._client_wrapper)

    def get_daily_forecast_past_forecast_daily_get(
        self,
        *,
        latitude: float,
        longitude: float,
        time: dt.datetime,
        timezone: typing.Optional[Timezone] = None,
        units: typing.Optional[Units] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DailyWeatherResponse:
        """
        Get daily weather forecast for a specific location and time

        Parameters
        ----------
        latitude : float

        longitude : float

        time : dt.datetime

        timezone : typing.Optional[Timezone]

        units : typing.Optional[Units]

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

        Returns
        -------
        DailyWeatherResponse
            Successful Response

        Examples
        --------
        import datetime

        from silurian import Earth

        client = Earth(
            api_key="YOUR_API_KEY",
        )
        client.get_daily_forecast_past_forecast_daily_get(
            latitude=47.6061,
            longitude=-122.3328,
            time=datetime.datetime.fromisoformat(
                "2024-01-01 00:00:00+00:00",
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "past/forecast/daily",
            method="GET",
            params={
                "latitude": latitude,
                "longitude": longitude,
                "time": serialize_datetime(time),
                "timezone": timezone,
                "units": units,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    DailyWeatherResponse,
                    parse_obj_as(
                        type_=DailyWeatherResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get_hourly_forecast_past_forecast_hourly_get(
        self,
        *,
        latitude: float,
        longitude: float,
        time: dt.datetime,
        timezone: typing.Optional[Timezone] = None,
        units: typing.Optional[Units] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HourlyWeatherResponse:
        """
        Get hourly weather forecast for a specific location and time

        Parameters
        ----------
        latitude : float

        longitude : float

        time : dt.datetime

        timezone : typing.Optional[Timezone]

        units : typing.Optional[Units]

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

        Returns
        -------
        HourlyWeatherResponse
            Successful Response

        Examples
        --------
        import datetime

        from silurian import Earth

        client = Earth(
            api_key="YOUR_API_KEY",
        )
        client.get_hourly_forecast_past_forecast_hourly_get(
            latitude=47.6061,
            longitude=-122.3328,
            time=datetime.datetime.fromisoformat(
                "2024-01-01 00:00:00+00:00",
            ),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "past/forecast/hourly",
            method="GET",
            params={
                "latitude": latitude,
                "longitude": longitude,
                "time": serialize_datetime(time),
                "timezone": timezone,
                "units": units,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    HourlyWeatherResponse,
                    parse_obj_as(
                        type_=HourlyWeatherResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


class AsyncEarth:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.

    Parameters
    ----------
    base_url : typing.Optional[str]
        The base url to use for requests from the client.

    environment : EarthEnvironment
        The environment to use for requests from the client. from .environment import EarthEnvironment



        Defaults to EarthEnvironment.PRODUCTION



    api_key : str
    timeout : typing.Optional[float]
        The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.

    follow_redirects : typing.Optional[bool]
        Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.

    httpx_client : typing.Optional[httpx.AsyncClient]
        The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.

    Examples
    --------
    from silurian import AsyncEarth

    client = AsyncEarth(
        api_key="YOUR_API_KEY",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: EarthEnvironment = EarthEnvironment.PRODUCTION,
        api_key: str,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.AsyncClient] = None,
    ):
        _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
        self._client_wrapper = AsyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            api_key=api_key,
            httpx_client=httpx_client
            if httpx_client is not None
            else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
            if follow_redirects is not None
            else httpx.AsyncClient(timeout=_defaulted_timeout),
            timeout=_defaulted_timeout,
        )
        self.weather = AsyncWeatherClient(client_wrapper=self._client_wrapper)

    async def get_daily_forecast_past_forecast_daily_get(
        self,
        *,
        latitude: float,
        longitude: float,
        time: dt.datetime,
        timezone: typing.Optional[Timezone] = None,
        units: typing.Optional[Units] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DailyWeatherResponse:
        """
        Get daily weather forecast for a specific location and time

        Parameters
        ----------
        latitude : float

        longitude : float

        time : dt.datetime

        timezone : typing.Optional[Timezone]

        units : typing.Optional[Units]

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

        Returns
        -------
        DailyWeatherResponse
            Successful Response

        Examples
        --------
        import asyncio
        import datetime

        from silurian import AsyncEarth

        client = AsyncEarth(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.get_daily_forecast_past_forecast_daily_get(
                latitude=47.6061,
                longitude=-122.3328,
                time=datetime.datetime.fromisoformat(
                    "2024-01-01 00:00:00+00:00",
                ),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "past/forecast/daily",
            method="GET",
            params={
                "latitude": latitude,
                "longitude": longitude,
                "time": serialize_datetime(time),
                "timezone": timezone,
                "units": units,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    DailyWeatherResponse,
                    parse_obj_as(
                        type_=DailyWeatherResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get_hourly_forecast_past_forecast_hourly_get(
        self,
        *,
        latitude: float,
        longitude: float,
        time: dt.datetime,
        timezone: typing.Optional[Timezone] = None,
        units: typing.Optional[Units] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HourlyWeatherResponse:
        """
        Get hourly weather forecast for a specific location and time

        Parameters
        ----------
        latitude : float

        longitude : float

        time : dt.datetime

        timezone : typing.Optional[Timezone]

        units : typing.Optional[Units]

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

        Returns
        -------
        HourlyWeatherResponse
            Successful Response

        Examples
        --------
        import asyncio
        import datetime

        from silurian import AsyncEarth

        client = AsyncEarth(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.get_hourly_forecast_past_forecast_hourly_get(
                latitude=47.6061,
                longitude=-122.3328,
                time=datetime.datetime.fromisoformat(
                    "2024-01-01 00:00:00+00:00",
                ),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "past/forecast/hourly",
            method="GET",
            params={
                "latitude": latitude,
                "longitude": longitude,
                "time": serialize_datetime(time),
                "timezone": timezone,
                "units": units,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    HourlyWeatherResponse,
                    parse_obj_as(
                        type_=HourlyWeatherResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    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, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


def _get_base_url(*, base_url: typing.Optional[str] = None, environment: EarthEnvironment) -> str:
    if base_url is not None:
        return base_url
    elif environment is not None:
        return environment.value
    else:
        raise Exception("Please pass in either base_url or environment to construct the client")
