# docs/03 - Premiers graphiques/scripts/plot_calendar_overview.py
from __future__ import annotations

from pathlib import Path
import sys

import pandas as pd

PROJECT_ROOT = Path(__file__).resolve().parents[3]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from meteo.dataset import load_raw_csv
from meteo.plots import (
    CalendarHeatmapSpec,
    daily_mean_series,
    generate_calendar_heatmaps,
    rainfall_daily_total_series,
)


DOC_DIR = Path(__file__).resolve().parent.parent
CSV_PATH = PROJECT_ROOT / "data" / "weather_minutely.csv"
OUTPUT_DIR = DOC_DIR / "figures" / "calendar"

HEATMAP_SPECS: tuple[CalendarHeatmapSpec, ...] = (
    CalendarHeatmapSpec(
        key="rain",
        agg_label="Pluie (mm)",
        title_template="Pluie quotidienne - {year}",
        cmap="Blues",
        colorbar_label="mm",
        aggregator=rainfall_daily_total_series,
    ),
    CalendarHeatmapSpec(
        key="temperature",
        agg_label="Température (°C)",
        title_template="Température moyenne quotidienne - {year}",
        cmap="coolwarm",
        colorbar_label="°C",
        aggregator=daily_mean_series("temperature"),
    ),
    CalendarHeatmapSpec(
        key="humidity",
        agg_label="Humidité relative (%)",
        title_template="Humidité relative quotidienne - {year}",
        cmap="PuBu",
        colorbar_label="%",
        aggregator=daily_mean_series("humidity"),
    ),
    CalendarHeatmapSpec(
        key="pressure",
        agg_label="Pression (hPa)",
        title_template="Pression moyenne quotidienne - {year}",
        cmap="Greens",
        colorbar_label="hPa",
        aggregator=daily_mean_series("pressure"),
    ),
    CalendarHeatmapSpec(
        key="illuminance",
        agg_label="Illuminance (lux)",
        title_template="Illuminance moyenne quotidienne - {year}",
        cmap="YlOrBr",
        colorbar_label="lux",
        aggregator=daily_mean_series("illuminance"),
    ),
    CalendarHeatmapSpec(
        key="wind",
        agg_label="Vent (km/h)",
        title_template="Vitesse moyenne du vent - {year}",
        cmap="Purples",
        colorbar_label="km/h",
        aggregator=daily_mean_series("wind_speed"),
    ),
)


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

    if not isinstance(df.index, pd.DatetimeIndex):
        print("⚠ Le dataset doit avoir un index temporel.")
        return

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

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

    latest_year = df.index.year.max()
    print(f"Année retenue pour le calendrier : {latest_year}")

    results = generate_calendar_heatmaps(
        df=df,
        specs=HEATMAP_SPECS,
        year=latest_year,
        output_dir=OUTPUT_DIR,
    )

    for result in results:
        title = result.spec.title_template.format(year=latest_year)
        if result.output_path:
            print(f"✔ {title} : {result.output_path}")
        else:
            reason = f" ({result.reason})" if result.reason else ""
            print(f"⚠ Heatmap ignorée pour {result.spec.key}{reason}.")

    print("✔ Graphiques calendrier générés.")


if __name__ == "__main__":
    main()
