#!/usr/bin/env python3
"""Download FINAPP data and plot neutron, muon, and pressure measurements."""

from __future__ import annotations

import argparse
import io
import sys
from pathlib import Path

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


DEFAULT_API_URL = (
    "https://data.finapptech.com/api/get-finapp-data/12023/NXYrp6yv"
)
DEFAULT_OUTPUT_DIR = Path("finapp-data")
TIME_COLUMN = "Datetime (UTC)"
PRESSURE_COLUMN = "Pressure [hPa]"
NEUTRON_COLUMN = "Raw Neutron Counts D1"
MUON_COLUMN = "Raw Muon Counts D1"
ACQUISITION_COLUMN = "Acquisition Time [s]"
MIN_VALID_NEUTRON_COUNTS = 500.0


class FinappApiError(RuntimeError):
    """Raised for invalid input or an unexpected FINAPP response."""


def parse_time(
    value: str | None, option: str, *, include_end_date: bool = False
) -> pd.Timestamp | None:
    if value is None:
        return None
    try:
        timestamp = pd.Timestamp(value)
    except ValueError as exc:
        raise argparse.ArgumentTypeError(
            f"Invalid {option} value {value!r}; use YYYY-MM-DD or ISO 8601."
        ) from exc
    if timestamp.tzinfo is None:
        timestamp = timestamp.tz_localize("UTC")
    else:
        timestamp = timestamp.tz_convert("UTC")
    if include_end_date and len(value.strip()) == 10:
        timestamp += pd.Timedelta(days=1)
    return timestamp


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Download FINAPP installation 12023 and plot raw neutron counts, "
            "raw muon counts, and pressure."
        )
    )
    parser.add_argument(
        "--start",
        help="Start of the time-series interval in UTC (YYYY-MM-DD or ISO time).",
    )
    parser.add_argument(
        "--end",
        help="End of the time-series interval in UTC (YYYY-MM-DD or ISO time).",
    )
    parser.add_argument(
        "--pressure-plot",
        action="store_true",
        help="Also create a raw-neutron-count versus pressure plot.",
    )
    parser.add_argument(
        "--pressure-start",
        help=(
            "Start of the neutron-versus-pressure interval. The main --start "
            "value is used when omitted."
        ),
    )
    parser.add_argument(
        "--pressure-end",
        help=(
            "End of the neutron-versus-pressure interval. The main --end "
            "value is used when omitted."
        ),
    )
    parser.add_argument(
        "--api-url",
        default=DEFAULT_API_URL,
        help="FINAPP API URL (default: installation 12023 supplied URL).",
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=DEFAULT_OUTPUT_DIR,
        help=f"Output directory (default: {DEFAULT_OUTPUT_DIR}).",
    )
    parser.add_argument("--show", action="store_true", help="Display the figures.")
    parser.add_argument(
        "--no-save",
        action="store_true",
        help="Do not save PDF and PNG plots; the downloaded CSV is always saved.",
    )
    return parser.parse_args()


def download_finapp(api_url: str) -> tuple[pd.DataFrame, str]:
    response = requests.get(
        api_url,
        headers={"User-Agent": "finapp-api-scientific-plotter/1.0"},
        timeout=180,
    )
    response.raise_for_status()
    text = response.content.decode(response.encoding or "utf-8-sig", errors="replace")
    try:
        frame = pd.read_csv(io.StringIO(text), sep=";")
    except pd.errors.ParserError as exc:
        raise FinappApiError("FINAPP returned an unreadable table.") from exc

    required = {
        TIME_COLUMN,
        PRESSURE_COLUMN,
        NEUTRON_COLUMN,
        MUON_COLUMN,
        ACQUISITION_COLUMN,
    }
    missing = required.difference(frame.columns)
    if missing:
        raise FinappApiError(
            "FINAPP response is missing required columns: " + ", ".join(sorted(missing))
        )
    frame[TIME_COLUMN] = pd.to_datetime(frame[TIME_COLUMN], utc=True, errors="coerce")
    for column in (
        PRESSURE_COLUMN,
        NEUTRON_COLUMN,
        MUON_COLUMN,
        ACQUISITION_COLUMN,
    ):
        frame[column] = pd.to_numeric(frame[column], errors="coerce")
    frame = (
        frame.dropna(subset=[TIME_COLUMN])
        .drop_duplicates(subset=[TIME_COLUMN], keep="last")
        .sort_values(TIME_COLUMN)
        .reset_index(drop=True)
    )
    if frame.empty:
        raise FinappApiError("FINAPP returned no valid timestamped records.")
    return frame, text


def select_interval(
    frame: pd.DataFrame,
    start: pd.Timestamp | None,
    end: pd.Timestamp | None,
    description: str,
) -> pd.DataFrame:
    if start is not None and end is not None and end <= start:
        raise FinappApiError(f"The {description} end must be later than its start.")
    selected = frame
    if start is not None:
        selected = selected.loc[selected[TIME_COLUMN] >= start]
    if end is not None:
        # A date-only end includes that entire UTC day.
        selected = selected.loc[selected[TIME_COLUMN] < end]
    if selected.empty:
        raise FinappApiError(f"No FINAPP records fall within the {description} interval.")
    return selected.copy()


def configure_dates(axis) -> None:
    locator = mdates.AutoDateLocator(minticks=5, maxticks=10)
    axis.xaxis.set_major_locator(locator)
    axis.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))


def time_series_figure(frame: pd.DataFrame):
    fig, axes = plt.subplots(
        3, 1, figsize=(11.0, 8.0), sharex=True, constrained_layout=True
    )
    specifications = (
        (NEUTRON_COLUMN, "Raw neutron counts D1", "#0072B2"),
        (MUON_COLUMN, "Raw muon counts D1", "#D55E00"),
        (PRESSURE_COLUMN, "Pressure (hPa)", "#009E73"),
    )
    for axis, (column, ylabel, color) in zip(axes, specifications):
        axis.plot(frame[TIME_COLUMN], frame[column], color=color, linewidth=0.8)
        axis.set_ylabel(ylabel)
        axis.grid(True, alpha=0.25)
    axes[0].set_title("FINAPP Kiel installation 12023")
    axes[-1].set_xlabel("Time (UTC)")
    configure_dates(axes[-1])
    return fig, axes


def select_interval_by_clicking(fig, axes) -> tuple[pd.Timestamp, pd.Timestamp]:
    """Let the user select the pressure-analysis interval with two clicks."""
    fig.suptitle(
        "Click once at the beginning and once at the end of the pressure-fit interval",
        fontsize=11,
    )
    fig.canvas.draw_idle()
    plt.figure(fig.number)
    points = plt.ginput(2, timeout=-1, show_clicks=True)
    if len(points) != 2:
        raise FinappApiError("The interactive interval selection was cancelled.")

    x0, x1 = sorted((points[0][0], points[1][0]))
    start = pd.Timestamp(mdates.num2date(x0)).tz_convert("UTC")
    end = pd.Timestamp(mdates.num2date(x1)).tz_convert("UTC")
    if end <= start:
        raise FinappApiError("The selected pressure-fit interval has zero width.")

    for axis in axes:
        axis.axvspan(start, end, color="#F0E442", alpha=0.22, zorder=0)
        axis.axvline(start, color="0.25", linestyle="--", linewidth=0.9)
        axis.axvline(end, color="0.25", linestyle="--", linewidth=0.9)
    fig.suptitle(
        f"Pressure-fit interval: {start:%Y-%m-%d %H:%M} to "
        f"{end:%Y-%m-%d %H:%M} UTC",
        fontsize=11,
    )
    fig.canvas.draw_idle()
    print(
        "Selected pressure-fit interval: "
        f"{start.isoformat()} to {end.isoformat()}"
    )
    return start, end


def pressure_figure(frame: pd.DataFrame):
    selected = frame.dropna(subset=[PRESSURE_COLUMN, NEUTRON_COLUMN])
    selected = selected.loc[selected[NEUTRON_COLUMN] >= MIN_VALID_NEUTRON_COUNTS]
    if selected.empty:
        raise FinappApiError(
            "No simultaneous neutron and pressure samples with at least "
            f"{MIN_VALID_NEUTRON_COUNTS:g} neutron counts are available."
        )

    pressure = selected[PRESSURE_COLUMN].to_numpy(dtype=float)
    neutrons = selected[NEUTRON_COLUMN].to_numpy(dtype=float)
    fig, axis = plt.subplots(figsize=(7.4, 5.4), constrained_layout=True)
    axis.scatter(pressure, neutrons, s=18, alpha=0.65, color="#0072B2")

    if len(selected) < 2 or np.ptp(pressure) <= 0:
        raise FinappApiError(
            "At least two valid measurements at different pressures are "
            "required for the exponential fit."
        )
    reference_pressure = float(np.mean(pressure))
    beta, log_n0 = np.polyfit(
        pressure - reference_pressure, np.log(neutrons), 1
    )
    n0 = float(np.exp(log_n0))
    xfit = np.linspace(pressure.min(), pressure.max(), 200)
    yfit = n0 * np.exp(beta * (xfit - reference_pressure))
    axis.plot(xfit, yfit, color="black", linewidth=1.2)
    correlation = float(np.corrcoef(pressure, np.log(neutrons))[0, 1])
    label = (
        f"Exponential fit: $N(P)={n0:.1f}\\,"
        f"\\exp[{beta:.4f}(P-{reference_pressure:.1f})]$\n"
        f"$r(P,\\ln N)={correlation:.3f}$"
    )
    axis.set_title("Raw neutron counts versus atmospheric pressure")
    axis.set_xlabel("Pressure (hPa)")
    axis.set_ylabel("Raw neutron counts D1")
    axis.grid(True, alpha=0.25)
    axis.text(
        0.02, 0.98, label, transform=axis.transAxes, va="top", ha="left",
        bbox={"facecolor": "white", "alpha": 0.85, "edgecolor": "0.7"},
    )
    parameters = {
        "fit_start_utc": selected[TIME_COLUMN].min().isoformat(),
        "fit_end_utc": selected[TIME_COLUMN].max().isoformat(),
        "n0_counts": n0,
        "reference_pressure_hpa": reference_pressure,
        "beta_per_hpa": float(beta),
        "correlation_pressure_log_counts": correlation,
        "number_of_fit_points": len(selected),
        "minimum_neutron_counts": MIN_VALID_NEUTRON_COUNTS,
    }
    return fig, parameters


def save_fit_parameters(parameters: dict, output_dir: Path) -> Path:
    output = output_dir / "finapp-neutron-pressure.csv"
    temporary = output.with_suffix(".csv.tmp")
    pd.DataFrame([parameters]).to_csv(temporary, index=False)
    temporary.replace(output)
    print(f"Saved pressure-fit parameters to {output.resolve()}")
    return output


def pressure_corrected_figure(frame: pd.DataFrame, parameters: dict):
    selected = frame.dropna(
        subset=[TIME_COLUMN, PRESSURE_COLUMN, NEUTRON_COLUMN, ACQUISITION_COLUMN]
    ).copy()
    selected = selected.loc[
        (selected[NEUTRON_COLUMN] >= MIN_VALID_NEUTRON_COUNTS)
        & (selected[ACQUISITION_COLUMN] > 0)
    ]
    if selected.empty:
        raise FinappApiError(
            "No valid measurements remain for the pressure-corrected count rate."
        )

    raw_rate = (
        selected[NEUTRON_COLUMN] / selected[ACQUISITION_COLUMN] * 3600.0
    )
    pressure_factor = np.exp(
        -parameters["beta_per_hpa"]
        * (selected[PRESSURE_COLUMN] - parameters["reference_pressure_hpa"])
    )
    corrected_rate = raw_rate * pressure_factor

    fig, axis = plt.subplots(figsize=(11.0, 5.4), constrained_layout=True)
    axis.plot(
        selected[TIME_COLUMN], raw_rate, color="#7F7F7F", linewidth=0.9,
        label="Uncorrected",
    )
    axis.plot(
        selected[TIME_COLUMN], corrected_rate, color="#0072B2", linewidth=1.1,
        label=(
            "Pressure corrected to "
            f"{parameters['reference_pressure_hpa']:.1f} hPa"
        ),
    )
    axis.set_title("FINAPP raw and pressure-corrected neutron count rate")
    axis.set_xlabel("Time (UTC)")
    axis.set_ylabel("Neutron count rate (counts h$^{-1}$)")
    axis.grid(True, alpha=0.25)
    axis.legend()
    configure_dates(axis)
    return fig


def save_figure(fig, stem: Path) -> None:
    fig.savefig(stem.with_suffix(".png"), dpi=300)
    fig.savefig(stem.with_suffix(".pdf"))
    print(f"Saved {stem.with_suffix('.png').resolve()}")
    print(f"Saved {stem.with_suffix('.pdf').resolve()}")


def main() -> int:
    args = parse_args()
    try:
        start = parse_time(args.start, "--start")
        end = parse_time(args.end, "--end", include_end_date=True)
        pressure_start = parse_time(args.pressure_start, "--pressure-start") or start
        pressure_end = (
            parse_time(
                args.pressure_end,
                "--pressure-end",
                include_end_date=True,
            )
            or end
        )

        frame, raw_text = download_finapp(args.api_url)
        args.output_dir.mkdir(parents=True, exist_ok=True)
        csv_file = args.output_dir / "finapp_installation_12023_raw.csv"
        temporary = csv_file.with_suffix(".csv.tmp")
        temporary.write_text(raw_text, encoding="utf-8")
        temporary.replace(csv_file)
        print(f"Saved {len(frame):,} records to {csv_file.resolve()}")

        time_frame = select_interval(frame, start, end, "time-series")
        time_figure, time_axes = time_series_figure(time_frame)
        figures = [time_figure]

        if args.pressure_plot:
            if (
                args.show
                and args.pressure_start is None
                and args.pressure_end is None
            ):
                pressure_start, pressure_end = select_interval_by_clicking(
                    time_figure, time_axes
                )
            pressure_frame = select_interval(
                frame, pressure_start, pressure_end, "pressure-plot"
            )
            pressure_fig, fit_parameters = pressure_figure(pressure_frame)
            figures.append(pressure_fig)
            save_fit_parameters(fit_parameters, args.output_dir)
            corrected_figure = pressure_corrected_figure(
                time_frame, fit_parameters
            )
            figures.append(corrected_figure)
            if not args.no_save:
                save_figure(
                    pressure_fig, args.output_dir / "finapp_neutrons_vs_pressure"
                )
                save_figure(
                    corrected_figure,
                    args.output_dir / "finapp_pressure_corrected_neutrons",
                )

        if not args.no_save:
            save_figure(time_figure, args.output_dir / "finapp_time_series")

        if args.show:
            plt.show()
        else:
            for figure in figures:
                plt.close(figure)
        return 0
    except (
        FinappApiError,
        requests.RequestException,
        argparse.ArgumentTypeError,
        OSError,
        ValueError,
    ) as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1


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