#!/usr/bin/env python3
"""Update pressure- and rigidity-corrected FINAPP neutron data every hour."""

from __future__ import annotations

import argparse
import sys
import time
from pathlib import Path

import matplotlib

# This program is intended to run without an attached graphical session.
matplotlib.use("Agg")
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests

from download_plot_finapp_api import (
    ACQUISITION_COLUMN,
    DEFAULT_API_URL,
    NEUTRON_COLUMN,
    PRESSURE_COLUMN,
    TIME_COLUMN,
    download_finapp,
    parse_time,
    select_interval,
)


SCRIPT_DIR = Path(__file__).resolve().parent
PARAMETER_FILE = SCRIPT_DIR / "finapp-data" / "finapp-neutron-pressure.csv"
OUTPUT_DIR = SCRIPT_DIR / "finapp-current"
OUTPUT_FILE = OUTPUT_DIR / "finapp_current_pressure_corrected_neutrons.png"
MAP_OUTPUT_FILE = OUTPUT_DIR / "finapp_current_polarstern_cutoff_map.png"
UPDATE_SECONDS = 3600.0
O2A_DATA_URL = "https://ingest.o2a-data.de/rest/data"
POLARSTERN_LATITUDE = "vessel:polarstern:hydrins_1:latitude"
POLARSTERN_LONGITUDE = "vessel:polarstern:hydrins_1:longitude"
OTSO_ALTITUDE_KM = 20.0
OTSO_SAMPLES = 12
DORMAN_ALPHA = 7.6
DORMAN_KAPPA = 0.88
MIN_VALID_CORRECTED_RATE = 150.0


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Download current FINAPP data every hour and update the raw and "
            "pressure-corrected neutron count-rate plot."
        )
    )
    parser.add_argument(
        "--start",
        required=True,
        help="Beginning of the plot interval in UTC (YYYY-MM-DD or ISO 8601).",
    )
    parser.add_argument(
        "--avg",
        default="6h",
        help="Time-based running-mean interval (default: 6h).",
    )
    return parser.parse_args()


def read_fit_parameters(path: Path) -> dict[str, float]:
    if not path.exists():
        raise FileNotFoundError(
            f"Fit parameter file not found: {path}. Run "
            "download_plot_finapp_api.py --pressure-plot first."
        )
    table = pd.read_csv(path)
    required = {"reference_pressure_hpa", "beta_per_hpa"}
    missing = required.difference(table.columns)
    if table.empty or missing:
        detail = ", ".join(sorted(missing)) or "no parameter row"
        raise ValueError(f"Invalid fit parameter file {path}: {detail}.")
    row = table.iloc[-1]
    return {
        "reference_pressure_hpa": float(row["reference_pressure_hpa"]),
        "beta_per_hpa": float(row["beta_per_hpa"]),
    }


def prepare_rates(
    frame: pd.DataFrame, parameters: dict[str, float]
) -> pd.DataFrame:
    selected = frame.dropna(
        subset=[TIME_COLUMN, PRESSURE_COLUMN, NEUTRON_COLUMN, ACQUISITION_COLUMN]
    ).copy()
    selected = selected.loc[
        (selected[NEUTRON_COLUMN] > 0)
        & (selected[ACQUISITION_COLUMN] > 0)
    ]
    if selected.empty:
        raise ValueError("No valid FINAPP neutron measurements remain after filtering.")

    selected["uncorrected_rate"] = (
        selected[NEUTRON_COLUMN] / selected[ACQUISITION_COLUMN] * 3600.0
    )
    selected["corrected_rate"] = selected["uncorrected_rate"] * np.exp(
        -parameters["beta_per_hpa"]
        * (selected[PRESSURE_COLUMN] - parameters["reference_pressure_hpa"])
    )
    return selected.sort_values(TIME_COLUMN).set_index(TIME_COLUMN)


def download_polarstern_positions(
    start: pd.Timestamp, end: pd.Timestamp
) -> pd.DataFrame:
    """Read hourly Polarstern positions from the public AWI/O2A service."""
    payload = {
        "sensors": [POLARSTERN_LATITUDE, POLARSTERN_LONGITUDE],
        "aggregate": "HOUR",
        "aggregateFunctions": ["MEAN"],
        "beginDate": start.strftime("%Y-%m-%d %H:%M:%S"),
        "endDate": end.strftime("%Y-%m-%d %H:%M:%S"),
        "limit": 0,
    }
    response = requests.post(
        O2A_DATA_URL,
        json=payload,
        headers={"Accept": "text/tab-separated-values"},
        timeout=180,
    )
    response.raise_for_status()
    table = pd.read_csv(pd.io.common.StringIO(response.text), sep="\t")
    if table.shape[1] < 3:
        raise ValueError("The AWI/O2A response contains no Polarstern positions.")
    positions = table.iloc[:, :3].copy()
    positions.columns = ["datetime", "latitude_deg", "longitude_deg"]
    positions["datetime"] = pd.to_datetime(
        positions["datetime"], utc=True, errors="coerce"
    )
    positions["latitude_deg"] = pd.to_numeric(
        positions["latitude_deg"], errors="coerce"
    )
    positions["longitude_deg"] = pd.to_numeric(
        positions["longitude_deg"], errors="coerce"
    )
    positions = positions.dropna().sort_values("datetime").drop_duplicates("datetime")
    positions = positions.loc[
        positions["latitude_deg"].between(-90, 90)
        & positions["longitude_deg"].between(-180, 180)
    ]
    if positions.empty:
        raise ValueError("No valid Polarstern positions were returned by AWI/O2A.")
    return positions


def select_otso_samples(positions: pd.DataFrame, count: int = OTSO_SAMPLES):
    number = min(count, len(positions))
    indices = np.unique(
        np.rint(np.linspace(0, len(positions) - 1, number)).astype(int)
    )
    return positions.iloc[indices].copy()


def calculate_vertical_cutoffs(samples: pd.DataFrame) -> pd.DataFrame:
    """Run OTSO with the same field settings as the Polarstern notebook."""
    try:
        import OTSO
    except ImportError as exc:
        raise RuntimeError(
            "The OTSO package is unavailable. Run this script in the OTSOenv "
            "Conda environment."
        ) from exc

    dates = [
        timestamp.to_pydatetime().replace(tzinfo=None)
        for timestamp in samples["datetime"]
    ]
    result = OTSO.flight(
        latitudes=samples["latitude_deg"].tolist(),
        longitudes=samples["longitude_deg"].tolist(),
        dates=dates,
        altitudes=[OTSO_ALTITUDE_KM] * len(samples),
        cutoff_comp="Vertical",
        magfield_params={
            "internalmag": "IGRF",
            "externalmag": "NONE",
            "magnetopause": "Kobel",
            "AdaptiveExternalModel": False,
        },
        computation_params={"corenum": 1, "Verbose": False},
        data_retrieval_params={"serverdata": "OFF", "livedata": "OFF"},
    )
    cutoff = result[0].copy()
    cutoff.columns = [str(column).strip() for column in cutoff.columns]
    date_column = next(
        column
        for column in cutoff.columns
        if column.lower() in {"date", "datetime", "time"}
    )
    rc_column = next(
        column for column in cutoff.columns if column.lower() == "rc"
    )
    output = pd.DataFrame(
        {
            "datetime": pd.to_datetime(cutoff[date_column], utc=True, errors="coerce"),
            "Rc_GV": pd.to_numeric(cutoff[rc_column], errors="coerce"),
        }
    ).dropna()
    if len(output) < 2:
        raise ValueError("OTSO returned fewer than two valid cutoff rigidities.")
    return output.sort_values("datetime").drop_duplicates("datetime")


def dorman_fraction(cutoff_rigidity) -> np.ndarray:
    rc = np.asarray(cutoff_rigidity, dtype=float)
    fraction = np.full(rc.shape, np.nan, dtype=float)
    zero = rc == 0
    positive = rc > 0
    fraction[zero] = 1.0
    with np.errstate(over="ignore", under="ignore", invalid="ignore"):
        inverse_power = np.exp(-DORMAN_KAPPA * np.log(rc[positive]))
        fraction[positive] = -np.expm1(-DORMAN_ALPHA * inverse_power)
    return fraction


def add_rigidity_correction(
    rates: pd.DataFrame, cutoffs: pd.DataFrame, average: str
) -> pd.DataFrame:
    output = rates.copy()
    sample_x = cutoffs["datetime"].astype("int64").to_numpy()
    rate_x = output.index.astype("int64").to_numpy()
    output["Rc_GV"] = np.interp(
        rate_x,
        sample_x,
        cutoffs["Rc_GV"].to_numpy(),
        left=cutoffs["Rc_GV"].iloc[0],
        right=cutoffs["Rc_GV"].iloc[-1],
    )
    response = dorman_fraction(output["Rc_GV"])
    output["pressure_rigidity_corrected_rate"] = output["corrected_rate"] / response
    # A fixed raw-count threshold incorrectly rejects valid measurements when
    # geomagnetic cutoff rigidity is high. Apply the switch-on/off rejection
    # only after both physical corrections.
    output = output.loc[
        output["pressure_rigidity_corrected_rate"]
        >= MIN_VALID_CORRECTED_RATE
    ].copy()
    output["pressure_corrected_running_mean"] = output["corrected_rate"].rolling(
        average, min_periods=2
    ).mean()
    output["corrected_running_mean"] = output[
        "pressure_rigidity_corrected_rate"
    ].rolling(average, min_periods=2).mean()
    return output


def add_cutoffs_to_positions(
    positions: pd.DataFrame, cutoffs: pd.DataFrame, rates: pd.DataFrame
) -> pd.DataFrame:
    output = positions.copy().sort_values("datetime")
    sample_x = cutoffs["datetime"].astype("int64").to_numpy()
    position_x = output["datetime"].astype("int64").to_numpy()
    output["Rc_GV"] = np.interp(
        position_x,
        sample_x,
        cutoffs["Rc_GV"].to_numpy(),
        left=np.nan,
        right=np.nan,
    )
    averaged_rates = (
        rates[["pressure_corrected_running_mean"]]
        .reset_index()
        .rename(columns={TIME_COLUMN: "datetime"})
        .dropna()
        .sort_values("datetime")
    )
    output = pd.merge_asof(
        output,
        averaged_rates,
        on="datetime",
        direction="nearest",
        tolerance=pd.Timedelta("45min"),
    )
    return output.dropna(subset=["Rc_GV"])


def create_position_map(track: pd.DataFrame, average: str):
    """Plot cutoff rigidity and pressure-corrected rates along the track."""
    try:
        import cartopy.crs as ccrs
        import cartopy.feature as cfeature
    except ImportError as exc:
        raise RuntimeError(
            "Cartopy is required for the Polarstern position map."
        ) from exc

    if track.empty:
        raise ValueError("No Polarstern track points with cutoff rigidity exist.")

    projection = ccrs.PlateCarree()
    figure = plt.figure(figsize=(11.0, 7.2))
    axis = figure.add_axes([0.08, 0.09, 0.61, 0.83], projection=projection)

    longitude = track["longitude_deg"].to_numpy()
    latitude = track["latitude_deg"].to_numpy()
    # Separate the two symbol series perpendicular to the local ship track.
    # The grey line and latest-position star remain at the true coordinates.
    latitude_scale = np.clip(np.cos(np.deg2rad(latitude)), 0.2, None)
    projected_longitude = longitude * latitude_scale
    delta_x = np.gradient(projected_longitude)
    delta_y = np.gradient(latitude)
    tangent_length = np.hypot(delta_x, delta_y)
    tangent_length[tangent_length == 0] = 1.0
    normal_x = -delta_y / tangent_length
    normal_y = delta_x / tangent_length
    half_separation_deg = 0.075
    rc_longitude = longitude - half_separation_deg * normal_x / latitude_scale
    rc_latitude = latitude - half_separation_deg * normal_y
    rate_longitude = longitude + half_separation_deg * normal_x / latitude_scale
    rate_latitude = latitude + half_separation_deg * normal_y
    lon_span = max(float(np.ptp(longitude)), 1.0)
    lat_span = max(float(np.ptp(latitude)), 1.0)
    lon_padding = max(2.0, 0.12 * lon_span)
    lat_padding = max(2.0, 0.12 * lat_span)
    axis.set_extent(
        [
            max(-180.0, longitude.min() - lon_padding),
            min(180.0, longitude.max() + lon_padding),
            max(-90.0, latitude.min() - lat_padding),
            min(90.0, latitude.max() + lat_padding),
        ],
        crs=projection,
    )
    axis.add_feature(cfeature.LAND, facecolor="0.92", edgecolor="none")
    axis.add_feature(cfeature.OCEAN, facecolor="#EAF4FA", edgecolor="none")
    axis.coastlines(resolution="110m", linewidth=0.7, color="0.25")
    axis.plot(
        longitude,
        latitude,
        color="0.35",
        linewidth=0.8,
        alpha=0.7,
        transform=projection,
        zorder=2,
    )
    points = axis.scatter(
        rc_longitude,
        rc_latitude,
        c=track["Rc_GV"],
        cmap="viridis",
        s=30,
        edgecolors="none",
        transform=projection,
        zorder=3,
        label="$R_c$ samples",
    )
    count_mask = track["pressure_corrected_running_mean"].notna().to_numpy()
    count_track = track.loc[count_mask]
    count_points = axis.scatter(
        rate_longitude[count_mask],
        rate_latitude[count_mask],
        c=count_track["pressure_corrected_running_mean"],
        cmap="plasma",
        marker="^",
        s=48,
        edgecolors="black",
        linewidths=0.25,
        transform=projection,
        zorder=4,
        label=f"Pressure corrected, {average} mean",
    )
    axis.scatter(
        longitude[-1],
        latitude[-1],
        marker="*",
        s=150,
        color="red",
        edgecolor="black",
        linewidth=0.5,
        transform=projection,
        zorder=5,
        label="Latest position",
    )
    gridlines = axis.gridlines(
        draw_labels=True, linewidth=0.5, color="0.5", alpha=0.45,
        linestyle="--",
    )
    gridlines.top_labels = False
    gridlines.right_labels = False
    count_color_axis = figure.add_axes([0.73, 0.17, 0.025, 0.66])
    rigidity_color_axis = figure.add_axes([0.86, 0.17, 0.025, 0.66])
    count_colorbar = figure.colorbar(count_points, cax=count_color_axis)
    count_colorbar.set_label(
        f"Pressure-corrected {average} mean (counts h$^{{-1}}$)"
    )
    rigidity_colorbar = figure.colorbar(points, cax=rigidity_color_axis)
    rigidity_colorbar.set_label("Vertical cutoff rigidity $R_c$ (GV)")
    axis.set_title("RV Polarstern: cutoff rigidity and neutron count rate")
    axis.legend(loc="best")
    return figure


def save_figure_atomically(figure, output: Path, dpi: int = 200) -> None:
    temporary = output.parent / f".{output.name}.tmp.png"
    figure.savefig(temporary, dpi=dpi)
    plt.close(figure)
    temporary.replace(output)


def create_figure(
    rates: pd.DataFrame, parameters: dict[str, float], average: str
):
    fig, axes = plt.subplots(
        2, 1, figsize=(11.0, 7.2), sharex=True, constrained_layout=True,
        gridspec_kw={"height_ratios": [3, 1]},
    )
    axis, rigidity_axis = axes
    axis.plot(
        rates.index,
        rates["uncorrected_rate"],
        color="#7F7F7F",
        linewidth=0.75,
        alpha=0.75,
        label="Uncorrected",
    )
    axis.plot(
        rates.index,
        rates["corrected_rate"],
        color="#0072B2",
        linewidth=0.9,
        alpha=0.75,
        label=(
            "Pressure corrected to "
            f"{parameters['reference_pressure_hpa']:.1f} hPa"
        ),
    )
    axis.plot(
        rates.index,
        rates["pressure_rigidity_corrected_rate"],
        color="#009E73",
        linewidth=1.0,
        alpha=0.8,
        label="Pressure and rigidity corrected",
    )
    axis.plot(
        rates.index,
        rates["corrected_running_mean"],
        color="#D55E00",
        linewidth=2.0,
        label=f"Fully corrected, {average} running mean",
    )
    axis.set_title("Current FINAPP neutron count rate")
    axis.set_ylabel("Neutron count rate (counts h$^{-1}$)")
    axis.grid(True, alpha=0.25)
    axis.legend()
    rigidity_axis.plot(
        rates.index, rates["Rc_GV"], color="#CC79A7", linewidth=1.2
    )
    rigidity_axis.set_ylabel("$R_c$ (GV)")
    rigidity_axis.set_xlabel("Time (UTC)")
    rigidity_axis.grid(True, alpha=0.25)
    locator = mdates.AutoDateLocator(minticks=5, maxticks=10)
    rigidity_axis.xaxis.set_major_locator(locator)
    rigidity_axis.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))
    return fig


def update_plot(start: pd.Timestamp, average: str) -> None:
    parameters = read_fit_parameters(PARAMETER_FILE)
    end = pd.Timestamp.now(tz="UTC")
    frame, _ = download_finapp(DEFAULT_API_URL)
    frame = select_interval(frame, start, end, "plot")
    rates = prepare_rates(frame, parameters)
    positions = download_polarstern_positions(start, end)
    position_samples = select_otso_samples(positions)
    cutoffs = calculate_vertical_cutoffs(position_samples)
    rates = add_rigidity_correction(rates, cutoffs, average)
    figure = create_figure(rates, parameters, average)
    track = add_cutoffs_to_positions(positions, cutoffs, rates)
    map_figure = create_position_map(track, average)

    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    cutoff_output = pd.merge_asof(
        position_samples.sort_values("datetime"),
        cutoffs.sort_values("datetime"),
        on="datetime",
        direction="nearest",
        tolerance=pd.Timedelta("1min"),
    )
    cutoff_output.to_csv(OUTPUT_DIR / "polarstern_otso_cutoffs.csv", index=False)
    track.to_csv(OUTPUT_DIR / "polarstern_track_with_cutoff.csv", index=False)
    save_figure_atomically(figure, OUTPUT_FILE)
    save_figure_atomically(map_figure, MAP_OUTPUT_FILE)
    print(
        f"[{pd.Timestamp.now(tz='UTC').isoformat()}] Updated "
        f"{OUTPUT_FILE.resolve()} and {MAP_OUTPUT_FILE.resolve()} "
        f"with {len(rates):,} measurements.",
        flush=True,
    )


def main() -> int:
    args = parse_args()
    try:
        start = parse_time(args.start, "--start")
        if start is None:
            raise ValueError("--start is required.")
        average_delta = pd.Timedelta(args.avg)
        if average_delta <= pd.Timedelta(0):
            raise ValueError("--avg must be a positive duration such as 6h or 1d.")
        average = args.avg
    except (ValueError, argparse.ArgumentTypeError) as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 2

    print(
        f"Starting hourly FINAPP updates from {start.isoformat()}. "
        "Stop with Ctrl-C.",
        flush=True,
    )
    try:
        while True:
            cycle_start = time.monotonic()
            try:
                update_plot(start, average)
            except (
                FileNotFoundError,
                ValueError,
                OSError,
                requests.RequestException,
                RuntimeError,
            ) as exc:
                print(
                    f"[{pd.Timestamp.now(tz='UTC').isoformat()}] "
                    f"Update failed: {exc}",
                    file=sys.stderr,
                    flush=True,
                )
            elapsed = time.monotonic() - cycle_start
            time.sleep(max(1.0, UPDATE_SECONDS - elapsed))
    except KeyboardInterrupt:
        print("FINAPP updater stopped.", flush=True)
        return 0


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