"""AgERA5 sources: CDS requests, downloads, and the list of daily inputs for r.in.gdal.

Chapter 1 builds a request by hand; Chapter 2 onward use these helpers.

Measured behaviour this module relies on (facts ledger):
- `area` crops on the server (A14); order is north, west, south, east.
- A one-year request (all months, days 01-31) is accepted, invalid dates are skipped,
  and arrives as a zip of one NetCDF per day named `..._AgERA5_YYYYMMDD_final-...nc` (A20).
- A local yearly archive file holds one band per day of the year (C25).
"""

from __future__ import annotations

import datetime as dt
import re
import zipfile
from pathlib import Path

DATE_IN_NAME = re.compile(r"_AgERA5_(\d{8})_")


def cds_request(cfg: dict, short: str, year: int, aoi: dict) -> dict:
    """CDS request for one variable, one whole year, cropped to `aoi` (edges)."""
    spec = cfg["agera5"]["variables"][short]
    request = {
        "variable": spec["cds"],
        "year": [str(year)],
        "month": [f"{m:02d}" for m in range(1, 13)],
        "day": [f"{d:02d}" for d in range(1, 32)],
        "version": cfg["agera5"]["version"],
        "area": [aoi["n"], aoi["w"], aoi["s"], aoi["e"]],
    }
    if spec["statistic"]:
        request["statistic"] = [spec["statistic"]]
    return request


def download_year(cfg: dict, short: str, year: int, aoi_name: str, dest: Path) -> Path:
    """Download and unzip one variable-year for an AOI. Skips work already done.

    Returns the folder holding the daily NetCDF files. Raises if the zip does not hold one
    file per day of the year.
    """
    dest = Path(dest)
    folder = dest / f"{short}_{year}_{aoi_name}"
    target = dest / f"agera5_{short}_{year}_{aoi_name}.zip"
    if not target.exists():
        import cdsapi  # only needed when a download really happens

        dest.mkdir(parents=True, exist_ok=True)
        request = cds_request(cfg, short, year, cfg["aoi"][aoi_name])
        partial = target.with_suffix(".part")  # an interrupted download never looks finished
        cdsapi.Client().retrieve(cfg["agera5"]["dataset"], request, str(partial))
        partial.replace(target)
    if not zipfile.is_zipfile(target):
        raise RuntimeError(f"{target} is not a zip archive; inspect it by hand")
    with zipfile.ZipFile(target) as z:
        members = [m for m in z.namelist() if m.endswith(".nc")]
        if not all((folder / m).exists() for m in members):  # first run, or interrupted unzip
            z.extractall(folder)
    days = (dt.date(year + 1, 1, 1) - dt.date(year, 1, 1)).days
    if len(members) != days:
        raise RuntimeError(f"{target.name} holds {len(members)} daily files, expected {days}")
    return folder


def date_from_name(name: str) -> dt.date:
    """Date of a daily CDS file, read from its name."""
    m = DATE_IN_NAME.search(name)
    if not m:
        raise ValueError(f"No date in file name: {name}")
    return dt.datetime.strptime(m.group(1), "%Y%m%d").date()


def gdal_name(path: Path, nc_var: str) -> str:
    """GDAL subdataset string for one variable in a NetCDF file."""
    return f'NETCDF:"{Path(path).as_posix()}":{nc_var}'


def archive_file(cfg: dict, short: str, year: int) -> Path | None:
    """Yearly file in the local archive, or None if no archive is configured or found."""
    root = cfg["paths"].get("agera5_archive")
    if not root:
        return None
    sub = cfg["agera5"]["variables"][short]["archive"]
    path = Path(root) / sub / f"agera5_{sub}_{year}.nc"
    return path if path.exists() else None


def daily_sources(cfg: dict, short: str, year: int, folder: Path | None = None) -> list[tuple]:
    """(date, gdal input, band) for every day of `year`.

    Uses the local archive when it has the year, otherwise the daily files in `folder`.
    """
    nc_var = cfg["agera5"]["variables"][short]["nc"]
    yearly = archive_file(cfg, short, year)
    if yearly is not None:
        n_days = (dt.date(year + 1, 1, 1) - dt.date(year, 1, 1)).days
        src = gdal_name(yearly, nc_var)
        return [(dt.date(year, 1, 1) + dt.timedelta(i), src, i + 1) for i in range(n_days)]
    if folder is None:
        raise FileNotFoundError(f"No archive for {short} {year} and no download folder given")
    out = [(date_from_name(f.name), gdal_name(f, nc_var), 1) for f in Path(folder).glob("*.nc")]
    return sorted(out)


def aoi_centres(aoi: dict, res: float = 0.1) -> tuple:
    """Latitude (north to south) and longitude cell centres of an AOI given by its edges."""
    import numpy as np

    rows = round((aoi["n"] - aoi["s"]) / res)
    cols = round((aoi["e"] - aoi["w"]) / res)
    lat = np.round(aoi["n"] - res / 2 - res * np.arange(rows), 4)
    lon = np.round(aoi["w"] + res / 2 + res * np.arange(cols), 4)
    return lat, lon


def staged_path(root: Path, short: str, year: int, aoi_name: str) -> Path:
    """Where the staged file of one variable-year lives."""
    return Path(root) / short / f"{short}_{year}_{aoi_name}.nc"


def check_staged(path: Path, nc_var: str, year: int, shape: tuple) -> None:
    """Raise unless `path` holds one map per day of `year`, in order, with `shape` cells."""
    import numpy as np
    import xarray as xr

    with xr.open_dataset(path) as ds:
        da = ds[nc_var]
        days = np.asarray(da["time"].values).astype("datetime64[D]")
        want = np.arange(f"{year}-01-01", f"{year + 1}-01-01", dtype="datetime64[D]")
        if days.shape != want.shape or not (days == want).all():
            raise RuntimeError(f"{path.name}: dates are not every day of {year} in order")
        if da.shape[1:] != tuple(shape):
            raise RuntimeError(f"{path.name}: {da.shape[1:]} cells, expected {tuple(shape)}")


def stage_year(cfg: dict, short: str, year: int, aoi_name: str, root: Path,
               downloads: Path | None = None) -> Path:
    """One small NetCDF holding every day of `year` for the AOI. Skips work already done.

    Source: the local archive when it has the year (cut to the AOI by nearest cell centre,
    ledger A17), otherwise the CDS daily files from `download_year` stacked along time.
    Each day is one chunk, so GDAL reads one band without decompressing its neighbours
    (archive chunks hold 31 days, ledger A22). Written to a temporary name first, so an
    interrupted run never leaves a file that looks finished.
    """
    import xarray as xr

    nc_var = cfg["agera5"]["variables"][short]["nc"]
    aoi = cfg["aoi"][aoi_name]
    lat, lon = aoi_centres(aoi, cfg["res"])
    target = staged_path(root, short, year, aoi_name)
    if target.exists():
        check_staged(target, nc_var, year, (lat.size, lon.size))
        return target

    yearly = archive_file(cfg, short, year)
    if yearly is not None:
        with xr.open_dataset(yearly) as ds:
            cut = ds[[nc_var, "crs"]].sel(lat=lat, lon=lon, method="nearest", tolerance=0.01)
            cut = cut.load()
    else:
        if downloads is None:
            raise FileNotFoundError(f"No archive for {short} {year} and no download folder")
        folder = download_year(cfg, short, year, aoi_name, downloads)
        days, crs = [], None
        for f in sorted(Path(folder).glob("*.nc"), key=lambda f: date_from_name(f.name)):
            with xr.open_dataset(f) as ds:
                days.append(ds[nc_var].load())
                if crs is None:  # daily files give crs a time axis of length 1
                    crs = xr.DataArray(ds["crs"].values.ravel()[0], attrs=ds["crs"].attrs)
        cut = xr.concat(days, dim="time").to_dataset()
        cut["crs"] = crs  # once, not stacked along time (ledger C66)
        cut = cut.sel(lat=lat, lon=lon, method="nearest", tolerance=0.01)

    cut[nc_var].encoding = {"zlib": True, "complevel": 1, "_FillValue": -9999.0,
                            "chunksizes": (1, lat.size, lon.size)}
    target.parent.mkdir(parents=True, exist_ok=True)
    partial = target.with_suffix(".part")
    cut.to_netcdf(partial)
    check_staged(partial, nc_var, year, (lat.size, lon.size))
    partial.replace(target)
    return target
