"""Rebuild the Newport Kelvin wave draft figures from the project's tide exports."""

import csv
from collections import defaultdict
from datetime import date, datetime, timedelta
from pathlib import Path
from statistics import mean
from zoneinfo import ZoneInfo

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, date2num
from matplotlib.ticker import MultipleLocator


HERE = Path(__file__).resolve().parent
DATA = HERE.parents[2] / "public" / "data"
PACIFIC = ZoneInfo("America/Los_Angeles")
START = date(2026, 9, 22)
END = date(2026, 11, 21)
TEAL = "#086b69"
NAVY = "#182e43"
GRAY = "#a4bac8"
AMBER = "#f4d6a5"
COASTAL_COLUMNS = ("Los Angeles (inches)", "La Jolla (inches)", "San Diego (inches)")
BEFORE = (date(2026, 10, 3), date(2026, 10, 6))
DURING = (date(2026, 10, 8), date(2026, 10, 11))

plt.rcParams.update({
    "font.family": "DejaVu Sans",
    "font.size": 11,
    "text.color": NAVY,
    "axes.labelcolor": NAVY,
    "axes.edgecolor": "#c7d2dc",
    "xtick.color": NAVY,
    "ytick.color": NAVY,
    "axes.spines.top": False,
    "axes.spines.right": False,
})


def load_hourly():
    days = defaultdict(list)
    with (DATA / "tides/yacht-basin-hourly-tides.csv").open() as source:
        for row in csv.DictReader(source):
            stamp = datetime.fromisoformat(row["time_utc"]).astimezone(PACIFIC)
            measured = row["yacht_basin_ft_mllw"]
            predicted = row["noaa_predicted_ft_mllw"]
            if START <= stamp.date() <= END and measured and predicted:
                days[stamp.date()].append((stamp, float(measured), float(predicted)))
    return days


def load_coastal():
    with (DATA / "ocean/regional-noaa-gauge-residuals.csv").open() as source:
        return {
            date.fromisoformat(row["date_utc"]): [
                float(row[key]) if row[key] else float("nan") for key in COASTAL_COLUMNS
            ]
            for row in csv.DictReader(source)
        }


def mean_excess(hours):
    if len(hours) < 18:
        return float("nan")
    return mean((measured - predicted) * 12 for _, measured, predicted in hours)


def export_plot(fig, name):
    fig.savefig(HERE / f"{name}.png", dpi=170, facecolor="white")
    plt.close(fig)


def window_mean(days, values, window):
    start, end = window
    return mean(value for day, value in zip(days, values) if start <= day <= end)


def arrival_figure(days, newport):
    fig, ax = plt.subplots(figsize=(9.8, 5.1), layout="constrained")
    before = window_mean(days, newport, BEFORE)
    during = window_mean(days, newport, DURING)
    arrival = date2num(DURING[0])
    ax.set_axisbelow(True)
    ax.grid(axis="y", color="#e3ebf0")
    ax.set_title("Yacht Basin water levels during Rachel", loc="left", weight="bold", fontsize=20, pad=17)
    ax.set_ylabel("Daily average above predicted tide (inches)")
    ax.set_ylim(10, 23.5)
    ax.set_xlim(date(2026, 10, 2), date(2026, 10, 16))
    ax.yaxis.set_major_locator(MultipleLocator(2))
    ax.set_xticks([date(2026, 10, day) for day in (2, 4, 6, 8, 10, 12, 14, 16)])
    ax.xaxis.set_major_formatter(DateFormatter("%b %d"))
    ax.axvspan(date2num(BEFORE[0]) - 0.5, date2num(BEFORE[1]) + 0.5, color=GRAY, alpha=0.21, lw=0)
    ax.axvspan(arrival - 0.5, date2num(DURING[1]) + 0.5, color=AMBER, alpha=0.47, lw=0)
    ax.axvline(arrival, color="#9a6220", linestyle=":", lw=1.4)
    ax.text(arrival + 0.18, 22.8, "Oct 8 · Rachel’s swell documented in Newport",
            color="#734711", fontsize=10.5, weight="bold", va="top")
    ax.plot(days, newport, color=TEAL, marker="o", markersize=4.5, lw=2, zorder=3)
    for window, average, color in [(BEFORE, before, NAVY), (DURING, during, "#905616")]:
        left, right = date2num(window)
        ax.hlines(average, left - 0.32, right + 0.32, color=color, linestyle="--", lw=1.6, zorder=4)
    ax.text(date2num(BEFORE[0]), before + 1.9, f"{before:.1f} in avg", weight="bold")
    ax.text(date2num(DURING[1]) - 0.05, during + 1.8, f"{during:.1f} in avg",
            color="#734711", weight="bold", ha="right")
    arrow_x = date2num(date(2026, 10, 14)) + 0.15
    ax.hlines([before, during], arrow_x - 0.2, arrow_x + 0.2, color=NAVY, lw=1.3)
    ax.annotate("", (arrow_x, during), (arrow_x, before),
                arrowprops={"arrowstyle": "<->", "color": NAVY, "lw": 1.8})
    ax.text(arrow_x + 0.15, (before + during) / 2, f"+{during - before:.1f} in",
            va="center", weight="bold", fontsize=13)
    export_plot(fig, "early-october-four-inch-bump")


def gauge_figure(days, newport, coastal):
    fig, ax = plt.subplots(figsize=(8.6, 4), layout="constrained")
    ax.set_title("The harbor and the coast rose together", loc="left", weight="bold", fontsize=19, pad=15)
    ax.set_xlabel("Increase in average water level above prediction (inches)")
    ax.set_axisbelow(True)
    ax.grid(axis="x", color="#e3ebf0")
    ax.set_xlim(0, 5)
    ax.xaxis.set_major_locator(MultipleLocator(1))
    labels = ["Newport Yacht Basin", "Los Angeles", "La Jolla", "San Diego"]
    ax.set_yticks(range(len(labels)), labels)
    ax.invert_yaxis()
    for pos, values in enumerate([newport, *zip(*coastal)]):
        change = window_mean(days, values, DURING) - window_mean(days, values, BEFORE)
        ax.barh(pos, change, color=TEAL if pos == 0 else GRAY, height=0.54)
        ax.text(change + 0.1, pos, f"+{change:.1f}", weight="bold", va="center")
    export_plot(fig, "early-october-rise-by-gauge")


def temperature_figure():
    with (DATA / "ocean/delmar-temperature.csv").open() as source:
        reader = csv.reader(source)
        _, *depth_columns = next(reader)
        records = {
            date.fromisoformat(day): [float(value) for value in values]
            for day, *values in reader
            if BEFORE[0].isoformat() <= day <= DURING[1].isoformat()
        }
    depths = [column.split(" (")[0] for column in depth_columns]
    dates = list(records)
    changes = [
        window_mean(dates, values, DURING) - window_mean(dates, values, BEFORE)
        for values in zip(*records.values())
    ]
    fig, ax = plt.subplots(figsize=(8.7, 4.2), layout="constrained")
    ax.set_title("The water warmed below the surface at Del Mar", loc="left",
                 weight="bold", fontsize=18, pad=16)
    ax.set_xlabel("Oct 8–11 average minus Oct 3–6 average (°C)")
    ax.set_axisbelow(True)
    ax.grid(axis="x", color="#e3ebf0")
    ax.axvline(0, color=NAVY, lw=1)
    ax.set_xlim(-1.15, 2.25)
    ax.xaxis.set_major_locator(MultipleLocator(0.5))
    ax.set_yticks(range(len(depths)), depths)
    ax.invert_yaxis()
    for position, change in enumerate(changes):
        color = TEAL if change >= 0 else GRAY
        ax.barh(position, change, color=color, height=0.53)
        positive = change >= 0
        offset = 0.06 if positive else -0.06
        label = "0.0" if abs(change) < 0.05 else f"{change:+.1f}"
        ax.text(change + offset, position, label,
                ha="left" if positive else "right", va="center", weight="bold")
    export_plot(fig, "early-october-del-mar-temperature")


def daily_figure(days, newport, coastal):
    fig, ax = plt.subplots(figsize=(10.8, 5.2), layout="constrained")
    ax.set_axisbelow(True)
    ax.grid(axis="y", color="#e3ebf0")
    ax.set_title("Extra water in Newport Bay rose in pulses", loc="left", weight="bold", fontsize=21, pad=19)
    ax.set_ylabel("Daily average above predicted tide (inches)")
    ax.set_ylim(0, 24)
    ax.yaxis.set_major_locator(MultipleLocator(4))
    ax.set_xlim(START, END)
    ax.set_xticks([START + timedelta(days=n) for n in (0, 8, 16, 25, 35, 40, 51, 60)])
    ax.xaxis.set_major_formatter(DateFormatter("%b %d"))
    for start, end, label in [(date(2026, 10, 8), date(2026, 10, 11), "Oct 8–11"),
                              (date(2026, 10, 24), date(2026, 10, 28), "Oct 24–28")]:
        ax.axvspan(start, end + timedelta(days=1), color=AMBER, alpha=0.5, lw=0)
        ax.text(start + timedelta(days=2), 21.5, label, ha="center", weight="bold", fontsize=10)
    ax.plot(days, newport, color=TEAL, lw=2.5, label="Newport Yacht Basin", zorder=3)
    ax.fill_between(days, [min(values) for values in coastal], [max(values) for values in coastal],
                    color=GRAY, alpha=0.63, label="Range at three NOAA coastal gauges")
    ax.legend(loc="lower right", frameon=False, fontsize=10)
    export_plot(fig, "daily-water-above-prediction")


def peak_figure(peaks):
    fig, ax = plt.subplots(figsize=(9.2, 4.6), layout="constrained")
    ax.set_axisbelow(True)
    ax.grid(axis="x", color="#e3ebf0")
    ax.set_title("October 27 reached higher on a bigger tide", loc="left", weight="bold", fontsize=20, pad=16)
    ax.set_xlabel("Water level (feet above mean lower low water)")
    ax.set_xlim(0, 9.3)
    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.set_yticks(range(len(peaks)), [stamp.strftime("%b %d") for stamp, _, _ in peaks])
    ax.set_ylim(len(peaks) - 0.28, -0.72)
    for pos, (_, measured, predicted) in enumerate(peaks):
        ax.barh(pos, predicted, color="#d9e5ed", height=0.48, label="Predicted tide" if pos == 0 else None)
        ax.barh(pos, measured - predicted, left=predicted, color=TEAL, height=0.48,
                label="Measured excess" if pos == 0 else None)
        ax.text(predicted - 0.14, pos, f"{predicted:.2f} ft", ha="right", va="center", weight="bold")
        ax.text((predicted + measured) / 2, pos, f"+{(measured - predicted) * 12:.1f} in",
                ha="center", va="center", color="white", weight="bold", fontsize=10)
        ax.text(measured + 0.10, pos, f"{measured:.2f} ft", va="center", weight="bold")
    ax.legend(loc="lower left", ncols=2, frameon=False, fontsize=10)
    export_plot(fig, "october-high-water")


def main():
    hours = load_hourly()
    regional = load_coastal()
    days = [START + timedelta(days=n) for n in range((END - START).days + 1)]
    newport = [mean_excess(hours[day]) for day in days]
    coastal = [regional[day] for day in days]
    peaks = [max(hours[date(2026, 10, day)], key=lambda hour: hour[1]) for day in (10, 27)]
    with (HERE / "daily-chart-data.csv").open("w", newline="") as output:
        writer = csv.writer(output)
        writer.writerow(["Date", "Yacht Basin paired hours (Pacific)", "Yacht Basin (inches, Pacific)", *COASTAL_COLUMNS])
        for day, local, coast in zip(days, newport, coastal):
            writer.writerow([day, len(hours[day]), round(local, 5), *coast])
    with (HERE / "high-water-chart-data.csv").open("w", newline="") as output:
        writer = csv.writer(output)
        writer.writerow(["Time (Pacific)", "Measured feet MLLW", "Predicted feet MLLW"])
        writer.writerows((stamp.isoformat(), measured, predicted) for stamp, measured, predicted in peaks)
    daily_figure(days, newport, coastal)
    arrival_figure(days, newport)
    gauge_figure(days, newport, coastal)
    temperature_figure()
    peak_figure(peaks)


if __name__ == "__main__":
    main()
