#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 2025
Author: charna
Download daily CMIP6 projections (precip, humidity, temperature)
for East Africa AOI, years 2030, 2050, 2070
"""

# pip install earthengine-api geemap

import time
from datetime import datetime
import ee
import geemap

# --------------------
# Initialize Earth Engine
# --------------------
try:
    ee.Initialize(project='dengue-project-470500')  # ✅ Use your GCP project ID
except Exception:
    ee.Authenticate()
    ee.Initialize(project='dengue-project-470500')

# --------------------
# Settings
# --------------------
AOI_ASSET = "projects/earth-tedto/assets/merged_east_africa"
#MODEL = "HadGEM3-GC31-MM"
MODEL = "MPI-ESM1-2-LR"
SCENARIOS = ["ssp245"]   # Choose the scenarios you need  #ssp370
YEARS = [2030, 2050, 2070]
VARIABLES = ["pr", "hurs", "tas"]  # precip, humidity, temperature
DRIVE_FOLDER = "GEE_EA_DAILY"
SCALE = 27830   # native resolution of GDDP-CMIP6 ~0.25°
CRS = "EPSG:4326"

# --------------------
# Load AOI
# --------------------
AOI = ee.FeatureCollection(AOI_ASSET).geometry()
CMIP6 = ee.ImageCollection("NASA/GDDP-CMIP6")


def check_resolution(model, scenario, var, year=2030):
    start = ee.Date.fromYMD(year, 1, 1)
    coll = (CMIP6.filterDate(start, start.advance(1, "year"))
                  .filter(ee.Filter.eq("model", model))
                  .filter(ee.Filter.eq("scenario", scenario))
                  .filter(ee.Filter.eq("variable", var))
                  .select(var))
    count = coll.size().getInfo()
    if count == 0:
        res = "❌ no data"
    elif count > 300:
        res = f"✅ daily ({count} images)"
    elif count > 10:
        res = f"✅ monthly ({count} images)"
    else:
        res = f"⚠️ unusual count ({count})"
    return res

# Example check
for var in ["pr", "tas", "hurs"]:
    print(f"{var}: {check_resolution('MPI-ESM1-2-LR', 'ssp245', var)}")
    print(f"{var}: {check_resolution('MPI-ESM1-2-LRd', 'ssp585', var)}")


# --------------------
# Helper: Daily stack builder
# --------------------
def daily_stack(var, year, scenario):
    start = ee.Date.fromYMD(year, 1, 1)
    img_coll = (
        CMIP6.filterDate(start, start.advance(1, "year"))
             .filter(ee.Filter.eq("scenario", scenario))
             .filter(ee.Filter.eq("model", MODEL))
             .select(var)
             .sort("system:time_start")
    )
    
    # DEBUG: count images
    count = img_coll.size().getInfo()
    print(f"   Found {count} daily images for {MODEL}, {var}, {scenario}, {year}")
    if count == 0:
        return None

    def convert(img):
        dt = ee.Date(img.get("system:time_start")).format("YYYYMMdd")
        band = img
        if var == "tas":   # Kelvin → Celsius
            band = img.subtract(273.15)
        if var == "pr":    # kg m-2 s-1 → mm/day
            band = img.multiply(86400)
        return band.rename(ee.String(var).cat("_").cat(dt))

    return img_coll.map(convert).toBands().clip(AOI)



# --------------------
# Helper: Export image
# --------------------
def export_image(img, fname):
    task = ee.batch.Export.image.toDrive(
        image=img,
        description=fname,
        folder=DRIVE_FOLDER,
        fileNamePrefix=fname,
        region=AOI.bounds(),  # stays server-side
        scale=SCALE,
        crs=CRS,
        maxPixels=1e13
    )
    task.start()
    return task

# --------------------
# Helper: Monitor tasks
# --------------------
def monitor(tasks, interval=30):
    last = {}
    running = set(tasks)
    print(f"[{datetime.utcnow().isoformat()}Z] Monitoring {len(running)} tasks...")
    while running:
        time.sleep(interval)
        for t in list(running):
            st = t.status()
            state = st.get("state")
            desc = st.get("description", t.id)
            if last.get(t.id) != state:
                print(f"[{datetime.utcnow().isoformat()}Z] {desc}: {state}")
                last[t.id] = state
            if state in ("COMPLETED", "FAILED", "CANCELLED"):
                running.remove(t)
    print(f"[{datetime.utcnow().isoformat()}Z] ✅ All exports finished.")

# --------------------
# Main loop
# --------------------
tasks = []
for scn in SCENARIOS:
    for yr in YEARS:
        for var in VARIABLES:
            print(f"Preparing {var} for {yr} under {scn}...")
            img = daily_stack(var, yr, scn)

            if img is None:
                print(f" ⚠️ Skipping {var}-{yr}-{scn} (no images found)")
                continue
            
            fname = f"EA_{MODEL}_{var}_{scn}_{yr}_DAILY"
            t = export_image(img, fname)
            print(f" ▶ Started task: {fname}")
            tasks.append(t)

monitor(tasks, interval=30)
print("🎉 All exports dispatched — check your Google Drive folder:", DRIVE_FOLDER)
