#!/usr/bin/env python3
"""
Ancillary data of one day on a common time axis, with the transmissions shaded.

Panels (only those with data): temperatures (PA input, PA output, feed, outside),
RF power, power clamp.

In a notebook:
    from plot_ancillary import ancillary_mpl
    fig = ancillary_mpl("ancillary", "2026-10-17", catalog="catalog", start="10:30", end="13:20")

From the command line:
    python plot_ancillary.py ancillary/ 2026-10-17 --catalog catalog/ -o ancillary_2026-10-17.pdf
"""

import argparse
from pathlib import Path

import pandas as pd

from ingest_ancillary import load_ancillary, parse_times

PALETTE = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"]
INK, INK_MUTED, GRID, TX_SHADE = "#0b0b0b", "#52514e", "#e4e3df", "#9a9893"

# (source, column, label) per panel; series that aren't there are skipped
PANELS = [
    ("Temperature (°C)", [
        ("temperature", "pa_output_c", "PA output"),
        ("temperature", "pa_input_c", "PA input"),
        ("temperature", "feed_c", "Feed"),
        ("outside_temperature", "outside_c", "Outside"),
    ]),
    ("RF power (dBm)", [("rfpower", "rf_power_dbm", "RF power")]),
    ("Power (kW)", [("powerclamp", "power_kw", "Power clamp")]),
]


def _load(root, source, t0, t1, cache):
    if source not in cache:
        try:
            cache[source] = load_ancillary(root, source, t0, t1)
        except FileNotFoundError:
            cache[source] = None
    return cache[source]


def ancillary_mpl(root, date, catalog=None, start=None, end=None, width=12):
    """Stacked panels for one UTC day; `start`/`end` like '10:30' crop the time axis.
    With `catalog` (directory from build_catalog.py) the transmissions are shaded."""
    import matplotlib.dates as mdates
    import matplotlib.pyplot as plt

    day = pd.Timestamp(date).date()
    t0 = pd.Timestamp(f"{day} {start or '00:00'}", tz="UTC")
    t1 = pd.Timestamp(f"{day} {end}", tz="UTC") if end else t0.normalize() + pd.Timedelta(1, unit="D")
    cache = {}
    panels = []
    for title, series in PANELS:
        present = []
        for source, col, label in series:
            df = _load(root, source, t0, t1, cache)
            if df is not None and col in df and df[col].notna().any():
                present.append((df, col, label))
        if present:
            panels.append((title, present))
    if not panels:
        raise ValueError(f"no ancillary data for {day}")

    # Without start/end: show the span that has data.
    if not start or not end:
        lo = min(d["time"].min() for _, p in panels for d, _, _ in p)
        hi = max(d["time"].max() for _, p in panels for d, _, _ in p)
        t0, t1 = (t0 if start else lo), (t1 if end else hi)

    heights = [2.2 if len(p) > 1 else 1.2 for _, p in panels]
    fig, axes = plt.subplots(len(panels), 1, sharex=True, figsize=(width, sum(heights) + 0.8),
                             gridspec_kw={"height_ratios": heights, "hspace": 0.12})
    axes = list(axes) if len(panels) > 1 else [axes]

    tx = None
    if catalog is not None:
        tx = pd.read_csv(Path(catalog) / "transmissions.csv")
        for c in ("tx_time", "tx_end", "rec_end"):
            tx[c] = parse_times(tx[c])
        tx = tx[(tx["tx_time"] < t1) & (tx["rec_end"] > t0)]

    naive = lambda s: s.dt.tz_convert("UTC").dt.tz_localize(None)
    for ax, (title, present) in zip(axes, panels):
        if tx is not None:
            for a, b in zip(tx["tx_time"], tx["tx_end"]):
                if pd.notna(b):
                    ax.axvspan(a.tz_localize(None), b.tz_localize(None),
                               color=TX_SHADE, alpha=0.18, lw=0)
        for i, (df, col, label) in enumerate(present):
            d = df[(df["time"] >= t0) & (df["time"] <= t1)]
            # break the line at gaps instead of drawing straight across them
            step = d["time"].diff().dt.total_seconds()
            gap = step > max(10 * step.median(), 120)
            y = d[col].astype(float).where(~gap)
            color = PALETTE[i] if len(present) > 1 else INK
            ax.plot(naive(d["time"]), y, color=color, lw=1.0 if len(d) < 20000 else 0.6,
                    label=label)
        ax.set_ylabel(title, color=INK_MUTED, fontsize=9)
        ax.grid(color=GRID, lw=0.7)
        ax.set_axisbelow(True)
        for side in ("top", "right"):
            ax.spines[side].set_visible(False)
        for side in ("left", "bottom"):
            ax.spines[side].set_color(GRID)
        ax.tick_params(colors=INK_MUTED, labelsize=8.5)
        if len(present) > 1:
            ax.legend(loc="upper left", ncol=len(present), frameon=False, fontsize=8.5,
                      bbox_to_anchor=(0, 1.18), handlelength=1.5)

    ax = axes[-1]
    ax.set_xlim(t0.tz_localize(None), t1.tz_localize(None))
    span_h = (t1 - t0).total_seconds() / 3600
    step = 1 if span_h <= 10 else 2
    ax.xaxis.set_major_locator(mdates.HourLocator(interval=step))
    ax.xaxis.set_minor_locator(mdates.MinuteLocator(byminute=[0, 15, 30, 45] if step == 1 else [0, 30]))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
    note = ", transmissions shaded" if tx is not None else ""
    ax.set_xlabel(f"Time (UTC), {day}{note}", color=INK_MUTED, fontsize=9)
    fig.align_ylabels(axes)
    return fig


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("root", help="ancillary directory (from ingest_ancillary.py)")
    ap.add_argument("date", help="day to plot, e.g. 2026-10-17")
    ap.add_argument("--catalog", help="catalog directory, to shade the transmissions")
    ap.add_argument("--start", help="e.g. 10:30 (UTC)")
    ap.add_argument("--end", help="e.g. 13:20 (UTC)")
    ap.add_argument("--width", type=float, default=12)
    ap.add_argument("-o", "--out", type=Path, help="output file (.pdf, .png, .svg)")
    args = ap.parse_args(argv)
    fig = ancillary_mpl(args.root, args.date, args.catalog, args.start, args.end, args.width)
    if args.out:
        fig.savefig(args.out, dpi=200, bbox_inches="tight")
        print(f"written {args.out}")
    else:
        import matplotlib.pyplot as plt
        plt.show()


if __name__ == "__main__":
    main()
