#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ERA5-Land逐时7变量下载(独立版): skagit / gulkana / colorado_cameo / zhimenda(长江源).
不连内网, 本地攒文件, 不回传. 需CDS API key.

用法:
  1. 到 https://cds.climate.copernicus.eu/ 注册
  2. 页面右上角头像 → API key → 复制
  3. 把key粘贴到下面 CDS_KEY 变量
  4. py intl_era5land_standalone.py [basin名]
     不带参数 = 三个流域全跑
  5. 跑完后把 intl_era5land_out/ 文件夹拷到服务器 传输\ 目录

依赖: py -m pip install cdsapi
"""
import os, sys, time
from pathlib import Path

CDS_KEY = "34e9afd7-a6c8-4ff6-9d39-fcca289cbc39"

TMP = Path("intl_era5land_out")
TMP.mkdir(exist_ok=True)

# 下载框 (N, W, S, E) — 已包含缓冲
AREAS = {
    "skagit":          [49.40, -122.00, 47.80, -120.50],
    "zhimenda":        [35.81, 90.53, 32.39, 97.05],
    "gulkana":         [63.41, -146.91, 62.11, -145.21],
    "colorado_cameo":  [39.35, -108.30, 37.75, -106.10],
}

VARS = ["2m_temperature", "2m_dewpoint_temperature", "surface_pressure",
        "10m_u_component_of_wind", "10m_v_component_of_wind",
        "surface_solar_radiation_downwards", "total_precipitation"]

BASINS = sys.argv[1:] if len(sys.argv) > 1 else list(AREAS)


def download_basin(c, basin, area):
    for yr in range(2000, 2019):
        f = TMP / f"omfill_{basin}_{yr}.nc"
        if f.exists() and f.stat().st_size > 1_000_000:
            print(f"  {basin} {yr} 已存在", flush=True)
            continue

        print(f"  [{basin} {yr}] 提交请求...", flush=True)
        try:
            c.retrieve("reanalysis-era5-land", dict(
                variable=VARS,
                date=[f"{yr}-01-01/{yr}-12-31"],
                time=[f"{h:02d}:00" for h in range(24)],
                area=area,
                data_format="netcdf", download_format="unarchived"
            ), str(f))
            print(f"  [{basin} {yr}] OK ({f.stat().st_size//1024//1024}MB)", flush=True)
        except Exception as e:
            print(f"  [{basin} {yr}] 失败: {str(e)[:80]}", flush=True)
            time.sleep(30)


def main():
    if CDS_KEY.startswith("在这里"):
        print("请先填入CDS API key!")
        print("  注册: https://cds.climate.copernicus.eu/")
        print("  API key: 页面右上角头像 → API key")
        sys.exit(1)

    import cdsapi
    c = cdsapi.Client(url="https://cds.climate.copernicus.eu/api", key=CDS_KEY,
                      quiet=False, timeout=3600,
                      wait_until_complete=True, sleep_max=3600)

    for basin in BASINS:
        if basin not in AREAS:
            print(f"未知流域: {basin}, 可选: {list(AREAS)}")
            continue
        print(f"\n=== {basin} (2000-2018, {len(VARS)}变量) ===", flush=True)
        download_basin(c, basin, AREAS[basin])

    print(f"\n完成! 文件在 {TMP}/ 文件夹")
    print(f"拷到服务器: \\\\10.168.1.100\\bigdata\\aximan_lake_consolidated\\传输\\")


if __name__ == "__main__":
    main()
