#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 14 10:01:36 2024

@author: charna
"""

import ee
import time

# ---------- Initialize Earth Engine ----------
ee.Initialize(project='ee-mtedto')  # Use your project ID if different

# ---------- Config ----------
start_date = '2024-01-01'
end_date   = '2024-12-31'

# This is no longer needed since you're using a merged shapefile:
# selected_countries = ['Kenya', 'Uganda', 'Rwanda', 'Ethiopia', 'Sudan']

variables = [
    'dewpoint_temperature_2m',
    'temperature_2m',
    'surface_pressure',
    'total_precipitation_sum'
]

drive_folder = 'EarthEngineExports'
export_scale_m = 11132  # ~0.1 degree

# ---------- Load region from your uploaded shapefile ----------
# Replace this with your actual asset ID
merged_asset_path = 'projects/earth-tedto/assets/merged_east_africa'  # ← UPDATE THIS

selected_region = ee.FeatureCollection(merged_asset_path)

# ---------- Store tasks ----------
tasks = []

# ---------- Start exports ----------
for variable in variables:
    print(f"⏳ Preparing export for: {variable}")
    
    band = ee.ImageCollection('ECMWF/ERA5_LAND/DAILY_AGGR') \
                .filterDate(start_date, end_date) \
                .select(variable)

    image = band.toBands().clip(selected_region)

    task = ee.batch.Export.image.toDrive(
        image=image,
        description=f'ERA5L_{variable}_2024',
        folder=drive_folder,
        fileNamePrefix=f'merged_shapefile_ERA5L_{variable}_2024',
        scale=export_scale_m,
        region=selected_region.geometry(),  # ✅ Correct: use shapefile geometry
        crs='EPSG:4326',
        maxPixels=1e13,
        fileFormat='GeoTIFF'
    )
    
    task.start()
    print(f"🚀 Export started for {variable}. Task ID: {task.id}")
    tasks.append((variable, task))

# ---------- Monitor progress ----------
print("\n🔍 Monitoring task progress... (Ctrl+C to stop)\n")
try:
    while True:
        all_done = True
        for name, task in tasks:
            status = task.status()
            state = status['state']
            if state in ['READY', 'RUNNING']:
                all_done = False
            print(f"[{name}] Status: {state}")
            if 'error_message' in status:
                print(f"  ⚠️  Error: {status['error_message']}")
        print("-" * 40)
        if all_done:
            print("✅ All tasks completed.")
            break
        time.sleep(10)

except KeyboardInterrupt:
    print("🔴 Monitoring stopped by user.")

