"""Tests du graphique des sets par année."""

import matplotlib
from pathlib import Path

from lib.plots.sets_per_year import (
    compute_parts_per_year,
    compute_sets_per_year,
    plot_sets_per_year,
)


matplotlib.use("Agg")


def test_compute_sets_per_year_counts_and_sorts() -> None:
    """Compte les sets par année et renvoie une liste triée."""
    rows = [
        {"year": "2020"},
        {"year": "2019"},
        {"year": "2020"},
    ]

    series = compute_sets_per_year(rows)

    assert series == [(2019, 1), (2020, 2)]


def test_compute_parts_per_year_sums_and_sorts() -> None:
    """Somme les pièces par année et renvoie une liste triée."""
    rows = [
        {"year": "2020", "num_parts": "10"},
        {"year": "2019", "num_parts": "5"},
        {"year": "2020", "num_parts": "1"},
    ]

    series = compute_parts_per_year(rows)

    assert series == [(2019, 5), (2020, 11)]


def test_plot_sets_per_year_creates_figure(tmp_path: Path) -> None:
    """Génère un fichier image avec les jalons fournis."""
    enriched = tmp_path / "sets_enriched.csv"
    milestones = tmp_path / "milestones.csv"
    destination = tmp_path / "figures" / "step07" / "sets_per_year.png"
    enriched.write_text(
        "set_num,name,year,theme_id,num_parts,img_url,set_id,rebrickable_url,in_collection\n"
        "75936-1,T. rex Rampage,2019,602,3120,https://example,75936,https://example,true\n"
        "75944-1,Indominus rex vs. Ankylosaurus,2020,602,1000,https://example,75944,https://example,false\n"
    )
    milestones.write_text(
        "year,description\n"
        "2019,Diffusion LEGO Jurassic World: Legend of Isla Nublar\n"
    )

    plot_sets_per_year(enriched, milestones, destination)

    assert destination.exists()
    assert destination.stat().st_size > 0
