# scripts/plot_wind_conditionals.py
from __future__ import annotations

from pathlib import Path

from meteo.dataset import load_raw_csv
from meteo.analysis import (
    compute_wind_rose_distribution,
    filter_by_condition,
    compute_mean_wind_components,
)
from meteo.plots import plot_wind_rose, plot_wind_vector_series


CSV_PATH = Path("data/weather_minutely.csv")
OUTPUT_DIR = Path("figures/wind_conditionals")
RAIN_THRESHOLD = 0.2  # mm/h


def _export_wind_rose(df, label: str, filename: str) -> None:
    if df.empty:
        print(f"⚠ Pas de données pour {label}.")
        return

    frequencies, speed_labels, sector_size = compute_wind_rose_distribution(
        df=df,
        direction_sector_size=30,
        speed_bins=(0, 5, 15, 30, 50, float("inf")),
    )
    if frequencies.empty:
        print(f"⚠ Impossible de construire la rose pour {label}.")
        return

    output_path = OUTPUT_DIR / filename
    plot_wind_rose(
        frequencies=frequencies,
        speed_bin_labels=speed_labels,
        output_path=output_path,
        sector_size_deg=sector_size,
        cmap="plasma",
    )
    print(f"✔ Rose des vents ({label}) : {output_path}")


def main() -> None:
    if not CSV_PATH.exists():
        print(f"⚠ Fichier introuvable : {CSV_PATH}")
        return

    df = load_raw_csv(CSV_PATH)
    if df.empty:
        print("⚠ Dataset vide.")
        return

    print(f"Dataset minuté chargé : {CSV_PATH}")
    print(f"  Lignes   : {len(df)}")
    print(f"  Colonnes : {list(df.columns)}")
    print()

    if "rain_rate" not in df.columns:
        print("⚠ Colonne 'rain_rate' absente.")
        return

    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    rain_condition = df["rain_rate"].fillna(0.0) >= RAIN_THRESHOLD
    dry_condition = df["rain_rate"].fillna(0.0) < RAIN_THRESHOLD

    _export_wind_rose(df, "toutes conditions", "wind_rose_all.png")
    _export_wind_rose(filter_by_condition(df, condition=rain_condition), "pluie", "wind_rose_rain.png")
    _export_wind_rose(filter_by_condition(df, condition=dry_condition), "temps sec", "wind_rose_dry.png")

    # Vecteurs moyens par mois
    vector_df = compute_mean_wind_components(df=df, freq="1M")
    vector_path = OUTPUT_DIR / "wind_vectors_monthly.png"
    plot_wind_vector_series(
        vector_df=vector_df,
        output_path=vector_path,
        title="Vecteurs moyens du vent (mensuel)",
    )
    print(f"✔ Vecteurs de vent mensuels : {vector_path}")
    print("✔ Graphiques vent/pluie conditionnels générés.")


if __name__ == "__main__":
    main()
