"""Évolution annuelle du nombre moyen de minifigs par set."""

from pathlib import Path
from typing import List

import matplotlib.pyplot as plt

from lib.filesystem import ensure_parent_dir
from lib.rebrickable.stats import read_rows


def load_minifigs_per_year(path: Path, scope: str) -> List[tuple[int, float]]:
    """Charge les moyennes annuelles pour un scope donné."""
    rows = read_rows(path)
    values: List[tuple[int, float]] = []
    for row in rows:
        if row["scope"] != scope:
            continue
        values.append((int(row["year"]), float(row["average_minifigs_per_set"])))
    values.sort(key=lambda item: item[0])
    return values


def plot_minifigs_per_set_timeline(path: Path, destination_path: Path) -> None:
    """Trace l'évolution annuelle des minifigs par set (global vs filtré)."""
    filtered = load_minifigs_per_year(path, "filtered")
    catalog = load_minifigs_per_year(path, "catalog")
    if not filtered or not catalog:
        return
    filtered_years, filtered_values = zip(*filtered)
    catalog_years, catalog_values = zip(*catalog)

    fig, ax = plt.subplots(figsize=(12, 6))
    ax.plot(catalog_years, catalog_values, color="#888888", linestyle="--", linewidth=1.6, label="Catalogue global")
    ax.plot(filtered_years, filtered_values, color="#1f77b4", linewidth=2.2, marker="o", label="Thèmes filtrés")
    ax.set_xlabel("Année")
    ax.set_ylabel("Nombre moyen de minifigs par set")
    ax.set_title("Évolution des minifigs par set")
    ax.grid(True, linestyle="--", alpha=0.3)
    ax.legend(loc="upper left")

    ensure_parent_dir(destination_path)
    fig.tight_layout()
    fig.savefig(destination_path, dpi=160)
    plt.close(fig)
