"""The post's figures, in the light and dark styles of scipython.com.

    uv run figures.py [output_dir]

Each function takes the data and returns draw(theme), for save_figures.
"""

import sys
from pathlib import Path

import matplotlib

matplotlib.use("Agg")  # draw at 1 pixel per pixel, whatever the screen
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, Normalize, to_rgb
from matplotlib.ticker import FuncFormatter, MultipleLocator
from scipython_style import DPI, WIDTH_PX, save_figures

import analysis as A

W = WIDTH_PX / DPI
MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
# Labels set inside a coloured cell are near-black or white, by the cell's luminance.
DARK_TEXT, LIGHT_TEXT = "#24262B", "#FBFBFC"
MIN_AIRLINE_FLIGHTS = 5000  # in the latest twelve months, for the airlines' rankings


def ramp(theme):
    """A one-hue sequential ramp from the surface to the accent: light to dark on the
    light page and dark to light on the dark page, so that more is always stronger."""
    if theme["page"] == "#FBFBFC":
        return LinearSegmentedColormap.from_list("ramp", ["#EEF1F6", "#9DB7D1", theme["series"][0], "#0A3A5E"])
    return LinearSegmentedColormap.from_list("ramp", [theme["surface"], "#3E5C7E", "#6F98BE", "#C9DCEA"])


def text_on(rgb) -> str:
    r, g, b = (c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in to_rgb(rgb))
    return DARK_TEXT if 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.25 else LIGHT_TEXT


def percent_axis(ax, axis="x"):
    fmt = FuncFormatter(lambda v, _: f"{v:.0f}%")
    (ax.xaxis if axis == "x" else ax.yaxis).set_major_formatter(fmt)


def hgrid(ax, axis="x"):
    ax.grid(axis=axis, lw=1)
    ax.set_axisbelow(True)
    ax.tick_params(axis="y", length=0)


# -- Trend ------------------------------------------------------------------------


def trend(df):
    m = A.summarise(df, "month")

    def draw(theme):
        fig, axes = plt.subplots(3, 1, figsize=(W, 7.2), dpi=DPI, sharex=True, layout="constrained",
                                 height_ratios=[1, 1.4, 0.9])  # fmt: skip
        series = [
            (m.planned / 1000, "Flights planned\n(thousands)", None),
            (m.on_time_pct, "On time", "%"),
            (m.cancelled_pct, "Cancelled", "%"),
        ]
        for ax, (y, label, unit) in zip(axes, series):
            ax.plot(y.index, y.values, c=theme["accent"], lw=2)
            ax.set_ylabel(label)
            ax.grid(axis="y", lw=1)
            ax.set_axisbelow(True)
            if unit:
                percent_axis(ax, "y")
            ax.set_ylim(0, None)
            ax.yaxis.set_major_locator(plt.MaxNLocator(4))
        axes[1].set_ylim(40, 100)
        axes[-1].xaxis.set_major_locator(mdates.YearLocator())
        axes[-1].xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
        covid = m.planned.idxmin()
        axes[-1].set_xlim(m.index.min() - np.timedelta64(30, "D"), m.index.max() + np.timedelta64(30, "D"))
        axes[0].annotate("COVID-19", (covid, m.planned[covid] / 1000), xytext=(-95, 12),
                         textcoords="offset points", color=theme["muted"], fontsize=12,
                         arrowprops=dict(arrowstyle="-", color=theme["muted"], lw=1))  # fmt: skip
        return fig

    return draw


def calendar(df):
    m = A.summarise(df, "month").on_time_pct
    years = sorted(m.index.year.unique())
    grid = np.full((len(years), 12), np.nan)
    for t, v in m.items():
        grid[years.index(t.year), t.month - 1] = v

    def draw(theme):
        fig, ax = plt.subplots(figsize=(W, 0.5 * len(years) + 1.6), dpi=DPI, layout="constrained")
        cmap, norm = ramp(theme), Normalize(40, 95)
        ax.imshow(np.ma.masked_invalid(grid), cmap=cmap, norm=norm, aspect="auto")
        for i in range(len(years)):
            for j in range(12):
                if not np.isnan(grid[i, j]):
                    ax.text(j, i, f"{grid[i, j]:.0f}", ha="center", va="center", fontsize=12,
                            color=text_on(cmap(norm(grid[i, j]))))  # fmt: skip
        ax.set_xticks(range(12), MONTHS)
        ax.set_yticks(range(len(years)), years)
        ax.tick_params(length=0)
        ax.xaxis.tick_top()
        for s in ax.spines.values():
            s.set_visible(False)
        # White lines between the cells (the surface gap).
        ax.set_xticks(np.arange(-0.5, 12), minor=True)
        ax.set_yticks(np.arange(-0.5, len(years)), minor=True)
        ax.grid(which="minor", color=theme["page"], lw=2)
        ax.tick_params(which="minor", length=0)
        ax.set_xlabel("Percentage of flights on time", color=theme["muted"], fontsize=12)
        return fig

    return draw


# -- Airports and airlines --------------------------------------------------------


def airports(recent):
    s = A.summarise(recent, ["airport", "direction"]).on_time_pct.unstack()
    overall = A.summarise(recent, "airport").on_time_pct
    s = s.loc[overall.sort_values().index]
    mean = 100 * recent.on_time.sum() / recent.planned.sum()

    def draw(theme):
        fig, ax = plt.subplots(figsize=(W, 0.3 * len(s) + 1.2), dpi=DPI, layout="constrained")
        y = np.arange(len(s))
        ax.hlines(y, s.min(axis=1), s.max(axis=1), color=theme["line"], lw=2, zorder=1)
        for col, label, marker, colour in (("D", "Departures", "o", theme["series"][0]),
                                           ("A", "Arrivals", "s", theme["series"][1])):  # fmt: skip
            ax.plot(s[col], y, marker, ms=8, mfc=colour, mec=theme["page"], mew=1.5, ls="none", label=label, zorder=2)
        ax.axvline(mean, color=theme["muted"], lw=1, zorder=0)
        ax.text(mean, len(s) - 0.4, f" All airports: {mean:.0f}%", color=theme["muted"], fontsize=12, va="bottom")
        ax.set_yticks(y, s.index)
        ax.set_ylim(-0.7, len(s) + 0.4)
        percent_axis(ax)
        hgrid(ax)
        ax.set_xlabel("Flights on time")
        ax.legend(loc="lower right", handletextpad=0.2)
        return fig

    return draw


def big_airlines(recent):
    s = A.summarise(recent, "brand")
    return s[s.planned >= MIN_AIRLINE_FLIGHTS]


def dots(s, mean, mean_label, xlabel):
    """A dot plot of on-time percentages, sorted, with the overall mean marked."""

    def draw(theme):
        fig, ax = plt.subplots(figsize=(W, 0.27 * len(s) + 1.1), dpi=DPI, layout="constrained")
        y = np.arange(len(s))
        ax.plot(s.on_time_pct, y, "o", ms=8, mfc=theme["accent"], mec=theme["page"], mew=1.5, zorder=3)
        for yi, v in zip(y, s.on_time_pct):
            ax.text(v + 0.8, yi, f"{v:.0f}%", va="center", fontsize=11, color=theme["muted"], zorder=3)
        ax.axvline(mean, color=theme["muted"], lw=1, zorder=1)
        ax.text(mean, len(s) - 0.3, f" {mean_label}: {mean:.0f}%", fontsize=12, color=theme["muted"], va="bottom")
        ax.set_yticks(y, s.index)
        ax.set_ylim(-0.6, len(s) + 0.3)
        lo, hi = s.on_time_pct.min(), s.on_time_pct.max()
        ax.set_xlim(5 * np.floor((lo - 2) / 5), 5 * np.ceil((hi + 4) / 5))
        percent_axis(ax)
        ax.grid(lw=1)
        ax.set_axisbelow(True)
        ax.tick_params(axis="y", length=0)
        ax.set_xlabel(xlabel)
        return fig

    return draw


def airlines(recent):
    s = big_airlines(recent).sort_values("on_time_pct")
    mean = 100 * recent.on_time.sum() / recent.planned.sum()
    return dots(s, mean, "All flights", "Flights on time")


def airline_airport(recent, n_airlines=10, n_airports=14, min_flights=300):
    top_airlines = big_airlines(recent).planned.nlargest(n_airlines).index
    top_airports = A.summarise(recent, "airport").planned.nlargest(n_airports).index
    s = A.summarise(recent[recent.brand.isin(top_airlines) & recent.airport.isin(top_airports)], ["brand", "airport"])
    otp = s.on_time_pct.where(s.planned >= min_flights).unstack()
    otp = otp.loc[top_airlines, top_airports]
    # Order the airports and airlines by their overall punctuality, worst first.
    otp = otp[A.summarise(recent, "airport").on_time_pct[top_airports].sort_values().index]
    otp = otp.loc[A.summarise(recent, "brand").on_time_pct[top_airlines].sort_values().index]

    def draw(theme):
        fig, ax = plt.subplots(figsize=(W, 0.42 * len(otp) + 2.2), dpi=DPI, layout="constrained")
        cmap, norm = ramp(theme), Normalize(45, 90)
        cmap.set_bad(theme["page"])
        ax.imshow(np.ma.masked_invalid(otp.values), cmap=cmap, norm=norm, aspect="auto")
        for i in range(otp.shape[0]):
            for j in range(otp.shape[1]):
                v = otp.values[i, j]
                if not np.isnan(v):
                    ax.text(j, i, f"{v:.0f}", ha="center", va="center", fontsize=11, color=text_on(cmap(norm(v))))
        ax.set_xticks(range(otp.shape[1]), otp.columns, rotation=50, ha="left", rotation_mode="anchor")
        ax.set_yticks(range(otp.shape[0]), otp.index)
        ax.xaxis.tick_top()
        ax.tick_params(length=0)
        for sp in ax.spines.values():
            sp.set_visible(False)
        ax.set_xticks(np.arange(-0.5, otp.shape[1]), minor=True)
        ax.set_yticks(np.arange(-0.5, otp.shape[0]), minor=True)
        ax.grid(which="minor", color=theme["page"], lw=2)
        ax.tick_params(which="minor", length=0)
        ax.set_xlabel("Percentage of flights on time", color=theme["muted"], fontsize=12)
        return fig

    return draw


def differences(table, label):
    """Diverging bars: points above (blue) or below (red) the expected percentage."""
    s = table.sort_values("difference")

    def draw(theme):
        fig, ax = plt.subplots(figsize=(W, 0.27 * len(s) + 1.2), dpi=DPI, layout="constrained")
        y = np.arange(len(s))
        colours = [theme["series"][0] if v >= 0 else theme["series"][1] for v in s.difference]
        ax.barh(y, s.difference, height=0.6, color=colours)
        for yi, v in zip(y, s.difference):
            ax.text(v + (0.4 if v >= 0 else -0.4), yi, f"{v:+.1f}".replace("-", "\u2212"), va="center",
                    ha="left" if v >= 0 else "right",
                    fontsize=11, color=theme["muted"])  # fmt: skip
        ax.axvline(0, color=theme["ink"], lw=1)
        ax.set_yticks(y, s.index)
        ax.set_ylim(-0.6, len(s) - 0.4)
        ax.set_xlim(min(s.difference.min() - 4, -5), max(s.difference.max() + 3, 5))
        ax.xaxis.set_major_locator(MultipleLocator(5))
        hgrid(ax)
        ax.set_xlabel(label)
        return fig

    return draw


def countries(recent, min_flights=3000):
    arr = recent[recent.direction == "A"]
    s = A.summarise(arr, "country")
    s = s[s.planned >= min_flights].sort_values("on_time_pct")
    mean = 100 * arr.on_time.sum() / arr.planned.sum()
    return dots(s, mean, "All arrivals", "Arrivals on time")


def make_all(df, output_dir) -> list[Path]:
    recent = A.last_months(df)
    big = big_airlines(recent).index
    by_airline = A.compared_with_others(recent, "brand", ["airport", "direction", "month"])
    by_airport = A.compared_with_others(recent, "airport", ["brand", "direction", "month"])
    figures = {
        "trend": trend(df),
        "calendar": calendar(df),
        "airports": airports(recent),
        "airlines": airlines(recent),
        "airline-airport": airline_airport(recent),
        "airlines-compared": differences(by_airline.loc[by_airline.index.intersection(big)],
                                         "Difference from other airlines at the same airports (points)"),  # fmt: skip
        "airports-compared": differences(by_airport, "Difference from the same airlines elsewhere (points)"),
        "countries": countries(recent),
    }
    paths = []
    for name, draw in figures.items():
        paths += save_figures(draw, name, output_dir)
    return paths


if __name__ == "__main__":
    make_all(A.load(), Path(sys.argv[1]) if len(sys.argv) > 1 else Path("output"))
