#!/usr/bin/env python3
"""Download ECMWF SEAS5 soil temperature level 1, one file per initialization month."""

from pathlib import Path

import cdsapi


# Edit these settings as needed.
START_YEAR = 1981
START_MONTH = 1
END_YEAR = 2026
END_MONTH = 9
OUTDIR = Path.home() / "Data" / "ECMWF" / "SEAS5" / "STL1_6hourly"
FILE_TEMPLATE = "STL1_ECMWF_SYS51_{year}{month:02d}01.nc"

DATASET = "seasonal-original-single-levels"
LEADTIMES = [str(hour) for hour in range(6, 5161, 6)]


def main():
    OUTDIR.mkdir(parents=True, exist_ok=True)
    client = cdsapi.Client()

    for year in range(START_YEAR, END_YEAR + 1):
        first_month = START_MONTH if year == START_YEAR else 1
        last_month = END_MONTH if year == END_YEAR else 12

        for month in range(first_month, last_month + 1):
            target = OUTDIR / FILE_TEMPLATE.format(year=year, month=month)
            temporary = Path(f"{target}.part")

            if target.is_file() and target.stat().st_size > 0:
                print(f"SKIP: {target}")
                continue

            request = {
                "originating_centre": "ecmwf",
                "system": "51",
                "variable": ["soil_temperature_level_1"],
                "year": [str(year)],
                "month": [f"{month:02d}"],
                "day": ["01"],
                "leadtime_hour": LEADTIMES,
                "data_format": "netcdf",
                "area": [24, 101, 7, 111],
            }

            print(f"DOWNLOAD: {year}-{month:02d}-01 -> {target}")
            client.retrieve(DATASET, request, str(temporary))
            temporary.replace(target)

    print("DONE")


if __name__ == "__main__":
    main()

