"""Quick looks at what a step produced: draw it, and print the numbers worth checking.

Every chapter step that creates or changes maps or a time series ends with one of these, so
the reader looks at the result before building on it. Figures use matplotlib only.

Reading a GRASS map (`maps`, `read`) needs a running GRASS session and uses the current
computational region. The `array_*` functions, `summary` and `series` work on numpy arrays
and need no GRASS.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence

import numpy as np


def summary(a) -> dict:
    """Cell count, null (NaN) count, and min / mean / max of the non-null cells."""
    a = np.asarray(a, dtype=float)
    ok = np.isfinite(a)
    n = int(ok.sum())
    if n == 0:
        return {"cells": int(a.size), "null": int(a.size), "min": None, "mean": None, "max": None}
    v = a[ok]
    return {"cells": int(a.size), "null": int(a.size - n), "min": float(v.min()), "mean": float(v.mean()),
            "max": float(v.max())}


def format_summary(label: str, s: dict, units: str = "", digits: int = 2) -> str:
    """One line such as 'tmax: 2,048 cells, 1,324 null; min 20.1, mean 28.3, max 33.0 degC'."""
    head = f"{label}: {s['cells']:,} cells, {s['null']:,} null"
    if s["min"] is None:
        return head + "; no values"
    u = f" {units}" if units else ""
    return f"{head}; min {s['min']:.{digits}f}, mean {s['mean']:.{digits}f}, max {s['max']:.{digits}f}{u}"


def read(name: str) -> np.ndarray:
    """A GRASS raster in the current region as a float array, nulls as NaN.

    dtype=float64 matters for integer (CELL) maps: without it garray reads them as int32 and a
    null cell comes back as -2147483648 instead of NaN, which no isfinite() test catches.
    """
    import grass.script.array as garray

    return np.asarray(garray.array(name, null="nan", dtype=np.float64), dtype=float)


def region_extent() -> tuple[float, float, float, float]:
    """(west, east, south, north) of the current region, the `extent` matplotlib expects."""
    import grass.script as gs

    r = gs.region()
    return (float(r["w"]), float(r["e"]), float(r["s"]), float(r["n"]))


def array_maps(arrays: Sequence, titles: Sequence[str], units: str = "", *, extent=None, cmap: str = "viridis",
               vmin: float | None = None, vmax: float | None = None, center: float | None = None, ncols: int = 3,
               panel_width: float = 3.6, suptitle: str | None = None, digits: int = 2, categories=None):
    """Draw arrays side by side on one colour scale and print a summary line for each.

    One colour scale for every panel, so panels compare directly. The scale runs from the
    lowest to the highest value over all panels unless vmin / vmax are given. `center` gives a
    diverging scale around that value (for differences and anomalies). `categories`, a dict
    {value: label}, draws integer classes with a legend instead of a colour bar.
    Returns the list of summaries.
    """
    import matplotlib.pyplot as plt
    from matplotlib import colors

    arrays = [np.asarray(a, dtype=float) for a in arrays]
    if len(arrays) != len(titles):
        raise ValueError("one title per array")
    sums = [summary(a) for a in arrays]
    finite = [a[np.isfinite(a)] for a in arrays]
    allv = np.concatenate(finite) if any(f.size for f in finite) else np.array([0.0])
    lo = float(allv.min()) if vmin is None else vmin
    hi = float(allv.max()) if vmax is None else vmax
    if hi == lo:
        hi = lo + 1.0
    norm = None
    cmap_obj = plt.get_cmap(cmap)
    if categories:
        keys = sorted(categories)
        cmap_obj = plt.get_cmap(cmap, len(keys))
        norm = colors.BoundaryNorm([k - 0.5 for k in keys] + [keys[-1] + 0.5], len(keys))
    elif center is not None:
        half = max(abs(lo - center), abs(hi - center)) or 1.0
        norm = colors.TwoSlopeNorm(vcenter=center, vmin=center - half, vmax=center + half)
    else:
        norm = colors.Normalize(vmin=lo, vmax=hi)

    n = len(arrays)
    cols = min(ncols, n)
    rows = -(-n // cols)
    h, w = arrays[0].shape
    aspect = (h / w) if extent is None else (extent[3] - extent[2]) / (extent[1] - extent[0])
    fig, axes = plt.subplots(rows, cols, figsize=(panel_width * cols + 0.8, panel_width * aspect * rows + 0.9),
                             squeeze=False, constrained_layout=True)
    im = None
    for ax, a, t in zip(axes.flat, arrays, titles):
        im = ax.imshow(a, extent=extent, cmap=cmap_obj, norm=norm, interpolation="nearest")
        ax.set_title(t, fontsize=9)
        ax.tick_params(labelsize=7)
    for ax in list(axes.flat)[n:]:
        ax.axis("off")
    if categories:
        from matplotlib.patches import Patch

        keys = sorted(categories)
        handles = [Patch(color=cmap_obj(i), label=categories[k]) for i, k in enumerate(keys)]
        fig.legend(handles=handles, loc="outside right center", fontsize=8, frameon=False)
    else:
        cb = fig.colorbar(im, ax=axes, shrink=0.85)
        cb.set_label(units, fontsize=8)
        cb.ax.tick_params(labelsize=7)
    if suptitle:
        fig.suptitle(suptitle, fontsize=10)
    plt.show()
    for t, s in zip(titles, sums):
        print(format_summary(t, s, units, digits))
    return sums


def maps(names: Sequence[str], titles: Sequence[str] | None = None, units: str = "", **kwargs):
    """Read GRASS rasters in the current region and draw them with `array_maps`."""
    arrays = [read(n) for n in names]
    return array_maps(arrays, list(titles) if titles else [n.split("@")[0] for n in names], units,
                      extent=region_extent(), **kwargs)


def series(x, ys: Mapping[str, Sequence] | Sequence, units: str = "", *, title: str | None = None,
           xlabel: str | None = None, height: float = 3.0, width: float = 9.0, digits: int = 2, marker=None):
    """Line plot of one or more series against x, with min / mean / max printed per series."""
    import matplotlib.pyplot as plt

    if not isinstance(ys, Mapping):
        ys = {"": ys}
    fig, ax = plt.subplots(figsize=(width, height), constrained_layout=True)
    for label, y in ys.items():
        ax.plot(x, y, label=label or None, lw=1, marker=marker, ms=3)
    ax.set_ylabel(units, fontsize=9)
    if xlabel:
        ax.set_xlabel(xlabel, fontsize=9)
    if title:
        ax.set_title(title, fontsize=10)
    if len(ys) > 1 or next(iter(ys)):
        ax.legend(fontsize=8, frameon=False)
    ax.grid(alpha=0.3)
    plt.show()
    out = {}
    for label, y in ys.items():
        s = summary(y)
        out[label] = s
        print(format_summary(label or "series", s, units, digits).replace(" cells", " values"))
    return out


def array_hist(arrays: Mapping[str, object] | Sequence, units: str = "", *, bins: int = 40, title: str | None = None,
               height: float = 3.0, width: float = 6.5, digits: int = 2):
    """Histogram of the non-null values of one or more arrays, on shared bins."""
    import matplotlib.pyplot as plt

    if not isinstance(arrays, Mapping):
        arrays = {"": arrays}
    vals = {k: np.asarray(v, dtype=float).ravel() for k, v in arrays.items()}
    vals = {k: v[np.isfinite(v)] for k, v in vals.items()}
    allv = np.concatenate(list(vals.values())) if vals else np.array([])
    edges = np.histogram_bin_edges(allv if allv.size else [0, 1], bins=bins)
    fig, ax = plt.subplots(figsize=(width, height), constrained_layout=True)
    for k, v in vals.items():
        ax.hist(v, bins=edges, alpha=0.6 if len(vals) > 1 else 0.9, label=k or None)
    ax.set_xlabel(units, fontsize=9)
    ax.set_ylabel("cells", fontsize=9)
    if title:
        ax.set_title(title, fontsize=10)
    if len(vals) > 1:
        ax.legend(fontsize=8, frameon=False)
    ax.grid(alpha=0.3)
    plt.show()
    out = {}
    for k, v in vals.items():
        out[k] = summary(v)
        print(format_summary(k or "values", out[k], units, digits).replace(" cells", " values").replace(", 0 null", ""))
    return out
