"""OGGM v17a only: fixed geometry vs spinup geometry, in Gt and in m w.e.

Usage: python plot_oggm_fixed_vs_spinup.py
Output: plots/oggm_fixed_vs_spinup_*.png and .csv
"""
import os

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

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

C_FIX, C_SPIN, C_DIFF = '#2a78d6', '#eb6834', '#52514c'
PERIODS = {'1975-1999': ('1975', '1999'), '2000-2019': ('2000', '2019'), '2020-2025': ('2020', '2025'),
           '1975-2025': ('1975', '2025')}


def load(rid, run):
    df = pd.read_csv(os.path.join(DATA, f'{REGIONS[rid][0]}_model_oggm_v17a_{run}.csv'), parse_dates=['start_date'])
    area = 0.5 * (df.glacier_area_reference_start + df.glacier_area_reference_end)
    return pd.DataFrame({'mwe': df.glacier_change_observed.values, 'area': area.values,
                         'gt': (df.glacier_change_observed * area / 1000.).values}, index=df.start_date)


def cum(s):
    """Cumulative series with a zero at the start, on month-end boundaries."""
    idx = s.index.append(pd.DatetimeIndex([s.index[-1] + pd.offsets.MonthBegin(1)]))
    return pd.Series(np.r_[0, s.cumsum().values], index=idx)


def main():
    data = {rid: {run: load(rid, run) for run in ('fixedgeom', 'spinupgeom')} for rid in REGIONS}
    # global: Gt summed; m w.e. as total Gt over total area of that run
    glob = {}
    for run in ('fixedgeom', 'spinupgeom'):
        gt = sum(data[r][run]['gt'] for r in REGIONS)
        area = sum(data[r][run]['area'] for r in REGIONS)
        glob[run] = pd.DataFrame({'mwe': gt / area * 1000., 'area': area, 'gt': gt})
    data[0] = glob
    names = {0: ('glob', 'Global'), **REGIONS}

    for unit, ulabel in (('gt', 'Gt'), ('mwe', 'm w.e.')):
        fig, axes = plt.subplots(4, 5, figsize=(17, 12.5))
        for ax, rid in zip(axes.ravel(), names):
            f, s = cum(data[rid]['fixedgeom'][unit]), cum(data[rid]['spinupgeom'][unit])
            ax.plot(f.index, f.values, color=C_FIX, lw=1.5, label='fixed geometry')
            ax.plot(s.index, s.values, color=C_SPIN, lw=1.5, label='spinup geometry')
            ax.plot(f.index, (s - f).values, color=C_DIFF, lw=1.3, ls='--', label='spinup minus fixed')
            style_axis(ax)
            ax.xaxis.set_major_locator(matplotlib.dates.YearLocator(10))
            ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y'))
            ax.set_xlim(f.index[0], f.index[-1])
            ax.set_title(f'{rid}  {names[rid][1]}' if rid else 'Global', fontsize=9.5, color=INK, loc='left',
                         fontweight='bold' if rid == 0 else 'normal')
        fig.suptitle(f'OGGM v17a: fixed vs spinup geometry, cumulative mass change in {ulabel}', x=0.012, y=0.992,
                     ha='left', fontsize=14, color=INK, fontweight='bold')
        fig.text(0.012, 0.968, 'Zero at 1 Jan 1975. '
                 + ('Gt = m w.e. x each run\'s own reported area. ' if unit == 'gt' else 'Global m w.e. = total Gt over each run\'s total area. ')
                 + 'Independent y-axis per panel.', fontsize=9.5, color=MUTED, ha='left')
        h, l = axes[0, 0].get_legend_handles_labels()
        fig.legend(h, l, loc='lower center', ncol=3, frameon=False, fontsize=10)
        fig.tight_layout(rect=(0, 0.035, 1, 0.962))
        fig.savefig(os.path.join(OUT, f'oggm_fixed_vs_spinup_cum_{unit}.png'), dpi=130, facecolor='white')
        plt.close(fig)

    # table: period totals and differences
    rows = []
    for rid in names:
        f, s = data[rid]['fixedgeom'], data[rid]['spinupgeom']
        for pname, (y0, y1) in PERIODS.items():
            ff, ss = f.loc[y0:y1], s.loc[y0:y1]
            ny = len(ff) / 12
            rows.append(dict(rid=rid, region=names[rid][0], period=pname,
                             fixed_gt=ff['gt'].sum(), spinup_gt=ss['gt'].sum(), diff_gt=ss['gt'].sum() - ff['gt'].sum(),
                             fixed_mwe_yr=ff.mwe.sum() / ny, spinup_mwe_yr=ss.mwe.sum() / ny,
                             diff_mwe_yr=(ss.mwe.sum() - ff.mwe.sum()) / ny,
                             area_ratio=ss.area.mean() / ff.area.mean(),
                             rmsd_monthly_mwe=np.sqrt(((ss.mwe - ff.mwe) ** 2).mean())))
    t = pd.DataFrame(rows)
    t['diff_gt_pct'] = 100 * t.diff_gt / t.fixed_gt.abs()
    t['diff_mwe_pct'] = 100 * t.diff_mwe_yr / t.fixed_mwe_yr.abs()
    t.to_csv(os.path.join(OUT, 'oggm_fixed_vs_spinup.csv'), index=False)

    # rate difference per period, in m w.e./yr (comparable across regions), one panel per period
    fig, axes = plt.subplots(1, 3, figsize=(16, 6.2), sharey=True)
    order = list(names)
    for ax, pname in zip(axes, list(PERIODS)[:3]):
        p = t[t.period == pname].set_index('rid').loc[order]
        y = np.arange(len(order))
        ax.barh(y, p.diff_mwe_yr, height=0.62, color=[C_SPIN if v < 0 else C_FIX for v in p.diff_mwe_yr])
        style_axis(ax)
        ax.axvline(0, color=MUTED, lw=0.8)
        ax.set_yticks(y)
        ax.set_yticklabels([f'{r}  {names[r][1]}' if r else 'Global' for r in order], fontsize=9, color=INK)
        ax.invert_yaxis()
        ax.set_xlim(-1.0, 0.85)
        ax.set_title(pname, fontsize=11, color=INK, loc='left')
        for yi, (v, g) in enumerate(zip(p.diff_mwe_yr, p.diff_gt)):
            ax.text(v + 0.015 if v >= 0 else v - 0.015, yi, f'{v:+.2f}  ({g:+.0f} Gt)', va='center',
                    ha='left' if v >= 0 else 'right', fontsize=7.5, color=MUTED, clip_on=False)
    fig.suptitle('OGGM v17a: spinup minus fixed geometry, mean specific mass balance', x=0.012, y=0.985, ha='left',
                 fontsize=14, color=INK, fontweight='bold')
    fig.text(0.012, 0.935, 'm w.e. per year; in brackets the period total difference in Gt. '
             'Orange: spinup more negative. Blue: spinup less negative.', fontsize=9.5, color=MUTED, ha='left')
    fig.tight_layout(rect=(0, 0, 1, 0.92))
    fig.savefig(os.path.join(OUT, 'oggm_fixed_vs_spinup_rate_diff.png'), dpi=140, facecolor='white')
    plt.close(fig)

    pd.set_option('display.width', 250, 'display.max_rows', 200)
    for pname in PERIODS:
        print('\n', pname)
        print(t[t.period == pname].drop(columns=['period', 'rid']).round(3).to_string(index=False))


if __name__ == '__main__':
    main()
