import logging

from diskcache import Cache
import ee
import geopandas as gpd
import pandas as pd
from pathlib import Path

from .sentinel import get_sentinel_properties
from .worldclim import get_average_temperature_and_precipation

logger = logging.getLogger(__name__)
path_root = Path(__file__).resolve().parent

EE_PROJECT_HELP = (
    "To find your project name:\n"
    "  1. Go to https://console.cloud.google.com\n"
    "  2. At the top of the page, click the project selector\n"
    "  3. Copy the 'Project ID' (e.g. 'my-project-123')\n"
)


def autenticateEE(project: str | None = None) -> None:
    if project is None:
        raise ValueError(
            "A Google Cloud project name is required.\n" + EE_PROJECT_HELP
        )
    ee.Authenticate()
    ee.Initialize(project=project)
    
    
def _check_ee_authenticated() -> bool:
    try:
        ee.Number(1).getInfo()
        return True
    except ee.EEException:
        return False
    
def autenticateEE(project: str) -> None:
    ee.Authenticate()
    ee.Initialize(project=project)


def get_environment_data(
    gdf: gpd.GeoDataFrame,
    ndvi: bool = True,
    ndwi: bool = True,
    temperature: bool = True,
    precipitation: bool = True,
) -> pd.DataFrame:
    if not _check_ee_authenticated():
        raise RuntimeError(
            "Earth Engine is not authenticated. Please run:\n\n"
            "    import ecoenv\n"
            "    ecoenv.autenticateEE(project='your-project')\n\n"
            + EE_PROJECT_HELP
        )
        
    if not (ndvi or ndwi or temperature or precipitation):
        raise ValueError(
            "At least one of the following parameters must be True: "
            "ndvi, ndwi, temperature, precipitation."
        )

    try:
        env_data = None
        logger.info("Fetching fresh data from sources...")

        if ndvi or ndwi:
            env_data = get_sentinel_properties(gdf, 250, ndvi, ndwi)

        if temperature or precipitation:
            source = env_data if env_data is not None else gdf
            env_data = get_average_temperature_and_precipation(
                source, batch_size=5000, temperature=temperature, precipitation=precipitation
            )

        return env_data

    except Exception as e:
        logger.error(f"Critical error retrieving environment data: {e}", exc_info=True)
        return pd.DataFrame()
    
    
def clear_cache(sentinel: bool = True, worldclim: bool = True):
    """Remove os dados em cache da biblioteca."""
    if sentinel:
        Cache(path_root / ".sentinel_cache").clear()
    if worldclim:
        Cache(path_root / ".worldclim_cache").clear()