"""Illustration: every hydrological-year cycle of one model in one region, overlaid.

Usage: python plot_hydro_year_cycles.py [dataset_key] [region_id] [first_year] [last_year]
Defaults: huss (GloGEM) 11 2000 2025. Year Y means 1 Oct (Y-1) to 30 Sep (Y); for southern regions
(17-19) 1 Apr (Y) to 31 Mar (Y+1).
Output: plots/hydro_year_cycles_{dataset}_{region}.png
"""
import os
import sys

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from plot_overview import DATA, DATASETS, OUT, REGIONS, INK, MUTED, style_axis

SOUTH = (17, 18, 19)


def main(key='huss', rid=11, y0=2000, y1=2025):
    rid, y0, y1 = int(rid), int(y0), int(y1)
    df = pd.read_csv(os.path.join(DATA, f'{REGIONS[rid][0]}_{DATASETS[key][0]}.csv'), parse_dates=['start_date'])
    s = pd.Series(df.glacier_change_observed.values, index=df.start_date.dt.to_period('M'))
    first_month = 4 if rid in SOUTH else 10
    cycles = {}
    for y in range(y0, y1 + 1):
        start = pd.Period(f'{y}-04', 'M') if rid in SOUTH else pd.Period(f'{y - 1}-10', 'M')
        idx = pd.period_range(start, periods=12, freq='M')
        if idx[0] >= s.index[0] and idx[-1] <= s.index[-1]:
            cycles[y] = s[idx].values
    c = pd.DataFrame(cycles)                 # rows: month of the hydrological year, columns: year
    cum = pd.concat([pd.DataFrame(0., index=[-1], columns=c.columns), c.cumsum()]).reset_index(drop=True)
    labels = ['JFMAMJJASOND'[(first_month - 1 + i) % 12] for i in range(12)]
    jan = (12 - first_month + 1) % 12        # position of 1 January on the cumulative axis

    cmap = matplotlib.colormaps['Blues']
    years = list(c.columns)
    col = {y: cmap(0.3 + 0.7 * i / max(len(years) - 1, 1)) for i, y in enumerate(years)}
    total = c.sum()
    marked = sorted({total.idxmin(), total.idxmax(), years[-1]})

    fig, axes = plt.subplots(1, 2, figsize=(15, 6.4))
    ax = axes[0]
    for y in years:
        ax.plot(np.arange(12) + 0.5, c[y], color=col[y], lw=1.1)
    ax.plot(np.arange(12) + 0.5, c.mean(axis=1), color='#0b0b0b', lw=2.4, label=f'Mean of {len(years)} years')
    ax.set_title('Monthly balance (m w.e. per month)', fontsize=11, color=INK, loc='left')
    ax = axes[1]
    for y in years:
        ax.plot(np.arange(13), cum[y], color=col[y], lw=1.1)
    ax.plot(np.arange(13), cum.mean(axis=1), color='#0b0b0b', lw=2.4)
    for y in marked:  # a few direct labels at the line ends
        ax.annotate(f'{y}', (12, cum[y].iloc[-1]), xytext=(5, 0), textcoords='offset points', va='center',
                    fontsize=9, color=INK)
    ax.annotate('mean', (12, cum.mean(axis=1).iloc[-1]), xytext=(5, 0), textcoords='offset points', va='center',
                fontsize=9, color=INK, fontweight='bold')
    ax.set_title('Cumulative balance from the start of the hydrological year (m w.e.)', fontsize=11, color=INK, loc='left')
    for ax in axes:
        style_axis(ax)
        ax.set_xlim(0, 12)
        ax.set_xticks(np.arange(13))
        ax.set_xticklabels([])
        ax.set_xticks(np.arange(12) + 0.5, minor=True)
        ax.set_xticklabels(labels, minor=True, fontsize=10, color=MUTED)
        ax.tick_params(which='minor', length=0)
        ax.tick_params(labelsize=10)
        ax.axvline(jan, color=MUTED, lw=1, ls=':')
    axes[1].annotate('1 January', (jan, axes[1].get_ylim()[0]), xytext=(4, 6), textcoords='offset points',
                     fontsize=9, color=MUTED)
    axes[0].legend(loc='lower left', frameon=False, fontsize=10)
    sm = matplotlib.cm.ScalarMappable(norm=matplotlib.colors.Normalize(years[0], years[-1]),
                                      cmap=matplotlib.colors.LinearSegmentedColormap.from_list('b', [col[years[0]], col[years[-1]]]))
    cb = fig.colorbar(sm, ax=axes, orientation='horizontal', fraction=0.035, pad=0.09, aspect=60)
    cb.set_label('Hydrological year (year in which it ends)' if rid not in SOUTH else 'Hydrological year (year in which it starts)',
                 color=MUTED, fontsize=9.5)
    cb.outline.set_visible(False)
    cb.ax.tick_params(colors=MUTED, labelsize=9, length=0)
    shoulder = c.iloc[:jan].sum() if jan else None
    sub = (f'{len(years)} hydrological years, {years[0]} to {years[-1]}. Annual total: mean {total.mean():+.2f}, '
           f'sd {total.std():.2f} m w.e.')
    if shoulder is not None:
        sub += f' Balance before 1 January: mean {shoulder.mean():+.2f}, sd {shoulder.std():.2f}, range {shoulder.min():+.2f} to {shoulder.max():+.2f} m w.e.'
    fig.suptitle(f'{DATASETS[key][1]}: every hydrological year in {rid} {REGIONS[rid][1]}', x=0.012, y=0.985, ha='left',
                 fontsize=14, color=INK, fontweight='bold')
    fig.text(0.012, 0.935, sub, fontsize=9.5, color=MUTED, ha='left')
    fig.savefig(os.path.join(OUT, f'hydro_year_cycles_{key}_{REGIONS[rid][0]}.png'), dpi=140, facecolor='white',
                bbox_inches='tight')
    plt.close(fig)
    print(sub)
    print('monthly sd across years:', dict(zip(labels, c.std(axis=1).round(2))))
    print('extremes:', total.idxmin(), round(total.min(), 2), '|', total.idxmax(), round(total.max(), 2))


if __name__ == '__main__':
    main(*sys.argv[1:])
