#!/usr/bin/env python3
"""Draw fractional AR-frequency changes with AR climatology contours."""

import argparse
from pathlib import Path

import cartopy.crs as ccrs
from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter
from cartopy.util import add_cyclic_point
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm
import numpy as np

from plot_ar_common import load_ar_composite, splice
from plot_common import (
    GLOBAL_SEASONS,
    STATES,
    smooth_nan,
)


PRIMARY_AR = "GuanWaliser_v2"
CLIMATOLOGY_CONTOUR_LEVELS = (30.0,)
CLIMATOLOGY_CONTOUR_COLOR = "green"
CLIMATOLOGY_CONTOUR_LINEWIDTH = 2.0
RELATIVE_CHANGE_CONTOUR_LEVELS = (-100.0,-75.0,-50.0, -25.0, 25.0, 50.0, 75.0, 100.0, 150.0)
FIGSIZE = (15, 10.5)
WSPACE = 0.00
HSPACE = 0.25


def draw_rectangular_map(axis, lon, lat, color_field, contour_field, norm, cmap,
                         contour_levels, title, contour_color="black",
                         contour_linewidth=0.55, coastline_alpha=0.5,
                         contour_fmt="%+g"):
    color_cyclic, lon_cyclic = add_cyclic_point(color_field, coord=lon)
    contour_cyclic, _ = add_cyclic_point(contour_field, coord=lon)
    mesh = axis.pcolormesh(
        lon_cyclic, lat, color_cyclic, transform=ccrs.PlateCarree(),
        cmap=cmap, norm=norm, shading="auto", rasterized=True,
    )
    if np.any(np.isfinite(contour_cyclic)):
        contours = axis.contour(
            lon_cyclic, lat, contour_cyclic, levels=contour_levels,
            transform=ccrs.PlateCarree(), colors=contour_color,
            linewidths=contour_linewidth,
        )
        axis.clabel(contours, fmt=contour_fmt, fontsize=10, inline=True)
    axis.coastlines(linewidth=0.55, alpha=coastline_alpha)
    axis.set_global()
    axis.set_xticks(np.arange(-180, 181, 60), crs=ccrs.PlateCarree())
    axis.set_yticks(np.arange(-90, 91, 30), crs=ccrs.PlateCarree())
    axis.xaxis.set_major_formatter(LongitudeFormatter(dateline_direction_label=True))
    axis.yaxis.set_major_formatter(LatitudeFormatter())
    axis.tick_params(labelsize=10)
    axis.set_title(title, fontsize=10)
    return mesh


def make_figure(project_root: Path, output_dir: Path):
    path = project_root / f"composite_AR_{PRIMARY_AR}_BAM.nc"
    record = load_ar_composite(path)
    panels = []
    for season_label, nh_season, sh_season in GLOBAL_SEASONS:
        climatology = splice(record, "climatology", nh_season, sh_season)
        for state_variable, state_label in STATES:
            composite = splice(record, state_variable, nh_season, sh_season)
            fractional_change = np.full_like(composite, np.nan)
            reliable = climatology >= 0.02
            fractional_change[reliable] = (
                100.0 * (composite[reliable] - climatology[reliable])
                / climatology[reliable]
            )
            smoothed_fractional_change = smooth_nan(
                fractional_change, sigma=3.0,
            )
            climatology_percent = smooth_nan(climatology * 100.0, sigma=3.0)
            tropical_mask = np.abs(record["lat"]) <= 15.0
            fractional_change[tropical_mask, :] = np.nan
            smoothed_fractional_change[tropical_mask, :] = np.nan
            climatology_percent[tropical_mask, :] = np.nan
            panels.append((
                season_label, nh_season, sh_season, state_label,
                fractional_change, smoothed_fractional_change,
                climatology_percent,
            ))

    norm = TwoSlopeNorm(vmin=-60.0, vcenter=0.0, vmax=60.0)
    projection = ccrs.PlateCarree(central_longitude=180)
    fig, axes = plt.subplots(
        2, 2, figsize=FIGSIZE, subplot_kw={"projection": projection},
    )
    fig.subplots_adjust(
        left=0.045, right=0.985, bottom=0.12, top=0.97,
        wspace=WSPACE, hspace=HSPACE,
    )
    letters = iter("abcd")
    for axis, item in zip(axes.flat, panels):
        (
            season_label, nh_season, sh_season, state_label,
            fractional_change, smoothed_fractional_change, climatology,
        ) = item
        title = (
            f"({next(letters)}) {state_label} {season_label.lower()} "
            f"(NH {nh_season} + SH {sh_season})"
        )
        mappable = draw_rectangular_map(
            axis, record["lon"], record["lat"],
            fractional_change, smoothed_fractional_change, norm,
            "RdBu_r", RELATIVE_CHANGE_CONTOUR_LEVELS, title,
            contour_color="black",
            contour_fmt="%g",
        )
        climatology_cyclic, lon_cyclic = add_cyclic_point(
            climatology, coord=record["lon"],
        )
        axis.contour(
            lon_cyclic, record["lat"], climatology_cyclic,
            levels=CLIMATOLOGY_CONTOUR_LEVELS,
            transform=ccrs.PlateCarree(),
            colors=CLIMATOLOGY_CONTOUR_COLOR,
            linewidths=CLIMATOLOGY_CONTOUR_LINEWIDTH,
            zorder=1.6,
        )

    colorbar = fig.colorbar(
        mappable, ax=axes, orientation="horizontal", shrink=0.58, pad=0.05,
        label="AR frequency relative change (%)",
    )
    colorbar.ax.tick_params(labelsize=10)
    destination = output_dir / f"Figure_2_AR_{PRIMARY_AR}.png"
    output_dir.mkdir(parents=True, exist_ok=True)
    fig.savefig(destination, dpi=300, bbox_inches="tight")
    plt.close(fig)
    print(f"Saved {destination}")
    for stale in output_dir.glob("Figure_2_AR_*.png"):
        if stale != destination:
            stale.unlink()
    return destination


def main():
    package_root = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--project-root", type=Path, default=package_root)
    parser.add_argument("--output-dir", type=Path)
    args = parser.parse_args()
    root = args.project_root.resolve()
    make_figure(root, (args.output_dir or package_root).resolve())


if __name__ == "__main__":
    main()
