#!/usr/bin/env python3
"""Maintain an hourly rolling 30-day STIS and ACE/EPAM electron plot.

By default the program runs continuously and refreshes the files in
``current-stis`` once per hour.  Use ``--once`` for a single update.
"""

from __future__ import annotations

import argparse
import signal
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests

from plot_solar1_stis_electrons import (
    FLUX_NAMES,
    StisError,
    channel_label,
    despike_fluxes,
    download_ace_de4,
    download_data,
)


DEFAULT_OUTPUT = Path(__file__).resolve().parent / "current-stis"
STOP_REQUESTED = False


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Update a rolling 30-day plot of SOLAR-1/STIS 251 keV and "
            "ACE/EPAM DE4 and LEFS60 E4′ electron fluxes every hour."
        )
    )
    parser.add_argument(
        "--days", type=float, default=30.0,
        help="Length of the rolling interval in days (default: 30).",
    )
    parser.add_argument(
        "--interval", type=float, default=60.0, metavar="MINUTES",
        help="Refresh interval in minutes (default: 60).",
    )
    parser.add_argument(
        "--average", type=float, default=5.0, metavar="MINUTES",
        help="STIS averaging interval in minutes (default: 5).",
    )
    parser.add_argument(
        "--despike", action=argparse.BooleanOptionalAction, default=True,
        help="Despike STIS and the newest SWPC DE4 data (default: enabled).",
    )
    parser.add_argument(
        "--logy", action=argparse.BooleanOptionalAction, default=True,
        help="Use logarithmic y scaling (default: enabled).",
    )
    parser.add_argument("--yl", type=float, default=None, help="Optional lower y limit.")
    parser.add_argument("--yu", type=float, default=None, help="Optional upper y limit.")
    parser.add_argument(
        "--output-dir", type=Path, default=DEFAULT_OUTPUT,
        help=f"Output directory (default: {DEFAULT_OUTPUT}).",
    )
    parser.add_argument(
        "--once", action="store_true",
        help="Create one plot and exit instead of running continuously.",
    )
    return parser.parse_args()


def average_series(times: pd.Series, values: pd.Series, minutes: float) -> pd.DataFrame:
    if minutes <= 0:
        raise StisError("--average must be greater than zero.")
    frame = pd.DataFrame({"time": times, "flux": values}).dropna(subset=["time"])
    return (
        frame.set_index("time")[["flux"]]
        .resample(pd.to_timedelta(minutes, unit="min"))
        .mean()
        .dropna()
        .reset_index()
    )


def atomic_savefig(fig, destination: Path, **kwargs) -> None:
    temporary = destination.with_name(f".{destination.stem}.tmp{destination.suffix}")
    fig.savefig(temporary, **kwargs)
    temporary.replace(destination)


def create_update(args: argparse.Namespace) -> tuple[datetime, datetime]:
    end = datetime.now(timezone.utc).replace(second=0, microsecond=0)
    start = end - timedelta(days=args.days)
    print(f"Updating rolling plot: {start:%Y-%m-%d %H:%M} to {end:%Y-%m-%d %H:%M} UTC")

    stis = download_data(start, end)
    if args.despike:
        stis = despike_fluxes(stis)
    stis_name = f"{FLUX_NAMES[3]}_despiked" if args.despike else FLUX_NAMES[3]
    stis_flux = pd.to_numeric(stis[stis_name], errors="coerce")
    if args.logy:
        stis_flux = stis_flux.where(stis_flux > 0)
    stis_plot = average_series(stis["time"], stis_flux, args.average)

    ace = download_ace_de4(start, end, despike=args.despike)
    args.output_dir.mkdir(parents=True, exist_ok=True)

    plt.rcParams.update(
        {
            "font.size": 11,
            "axes.labelsize": 12,
            "axes.titlesize": 13,
            "axes.titleweight": "bold",
            "legend.fontsize": 10,
            "xtick.direction": "in",
            "ytick.direction": "in",
            "xtick.top": True,
            "ytick.right": True,
        }
    )
    fig, axis = plt.subplots(figsize=(11.0, 5.2), constrained_layout=True)
    axis.plot(
        stis_plot["time"], stis_plot["flux"], color="#D55E00", linewidth=1.0,
        label=f"SOLAR-1/STIS {channel_label(stis, 3)} ({args.average:g}-min mean)",
    )

    ace_lines = []
    if not ace.empty:
        de4 = ace["de4_per_kev"].where(ace["de4_per_kev"] > 0) if args.logy else ace["de4_per_kev"]
        de4_line = axis.plot(
            ace["time"], de4, color="#6A3D9A", linewidth=0.9,
            label="ACE/EPAM DE4 (175–315 keV)",
        )[0]
        ace_lines.append(de4_line)

        lefs60 = ace["lefs60_e4_per_kev"]
        if args.logy:
            lefs60 = lefs60.where(lefs60 > 0)
        if lefs60.notna().any():
            lefs_line = axis.plot(
                ace["time"], lefs60, color="#0072B2", linewidth=0.9,
                label="ACE/EPAM LEFS60 E4′ (175–290 keV)",
            )[0]
            ace_lines.append(lefs_line)
        else:
            lefs_line = axis.plot(
                [], [], color="#0072B2", linewidth=0.9,
                label="ACE/EPAM LEFS60 E4′ (no data in interval)",
            )[0]
            ace_lines.append(lefs_line)

    if args.logy:
        axis.set_yscale("log")

    # Match the second-panel convention: determine automatic limits from STIS
    # alone, extend the lower bound by one decade, and do not let noisy ACE
    # data control the range. Explicit --yl/--yu values take precedence.
    for line in ace_lines:
        line.set_visible(False)
    axis.relim(visible_only=True)
    axis.autoscale_view()
    for line in ace_lines:
        line.set_visible(True)
    lower, upper = axis.get_ylim()
    if args.logy and np.isfinite(lower) and lower > 0:
        lower /= 10.0
    lower = args.yl if args.yl is not None else lower
    upper = args.yu if args.yu is not None else upper
    if args.logy and lower <= 0:
        raise StisError("--yl must be greater than zero with logarithmic scaling.")
    if lower >= upper:
        raise StisError("--yl must be smaller than --yu.")
    axis.set_ylim(lower, upper)

    axis.set_xlim(start, end)
    axis.set_title(f"Rolling {args.days:g}-day electron comparison")
    axis.set_ylabel(
        r"Differential flux (cm$^{-2}$ s$^{-1}$ sr$^{-1}$ keV$^{-1}$)"
    )
    axis.set_xlabel("Time (UTC)")
    axis.grid(True, which="both", alpha=0.25)
    axis.legend(loc="best")
    locator = mdates.AutoDateLocator(minticks=6, maxticks=12)
    axis.xaxis.set_major_locator(locator)
    axis.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))

    png = args.output_dir / "current_stis_30days.png"
    pdf = args.output_dir / "current_stis_30days.pdf"
    atomic_savefig(fig, png, dpi=300)
    atomic_savefig(fig, pdf)
    plt.close(fig)

    stis_plot.to_csv(args.output_dir / "current_stis_251kev.csv", index=False)
    ace.to_csv(args.output_dir / "current_ace_epam.csv", index=False)
    (args.output_dir / "last_update_utc.txt").write_text(
        f"{end.isoformat()}\n", encoding="utf-8"
    )
    print(f"Updated {png.resolve()}")
    return start, end


def request_stop(_signum, _frame) -> None:
    global STOP_REQUESTED
    STOP_REQUESTED = True


def main() -> int:
    args = parse_args()
    if args.days <= 0 or args.interval <= 0:
        print("Error: --days and --interval must be greater than zero.", file=sys.stderr)
        return 2
    signal.signal(signal.SIGINT, request_stop)
    signal.signal(signal.SIGTERM, request_stop)

    while not STOP_REQUESTED:
        cycle_start = time.monotonic()
        try:
            create_update(args)
        except (StisError, requests.RequestException, ValueError, OSError) as exc:
            print(f"Update failed: {exc}", file=sys.stderr, flush=True)
            if args.once:
                return 1
        if args.once:
            return 0
        wait_seconds = max(1.0, args.interval * 60.0 - (time.monotonic() - cycle_start))
        print(f"Next update in {wait_seconds / 60.0:.1f} minutes", flush=True)
        deadline = time.monotonic() + wait_seconds
        while not STOP_REQUESTED and time.monotonic() < deadline:
            time.sleep(min(5.0, deadline - time.monotonic()))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
