"""Tests des graphiques sur la moyenne de pièces par set."""

from pathlib import Path

import matplotlib

from lib.plots.parts_per_set import (
    compute_average_parts_per_set,
    compute_rolling_mean,
    plot_parts_per_set,
)


matplotlib.use("Agg")


def test_compute_average_parts_per_set() -> None:
    """Calcule la moyenne annuelle pièces/set."""
    rows = [
        {"year": "2020", "num_parts": "100"},
        {"year": "2020", "num_parts": "200"},
        {"year": "2021", "num_parts": "150"},
    ]

    series = compute_average_parts_per_set(rows)

    assert series == [(2020, 150.0), (2021, 150.0)]


def test_compute_rolling_mean() -> None:
    """Calcule une moyenne glissante 2 ans."""
    series = [(2020, 100.0), (2021, 200.0), (2022, 300.0)]

    rolling = compute_rolling_mean(series, 2)

    assert rolling == [(2020, 0.0), (2021, 150.0), (2022, 250.0)]


def test_plot_parts_per_set_creates_figure(tmp_path: Path) -> None:
    """Génère le fichier image avec moyennes annuelle et glissante."""
    enriched = tmp_path / "sets_enriched.csv"
    milestones = tmp_path / "milestones.csv"
    destination = tmp_path / "figures" / "step07" / "avg_parts_per_set.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\n2019,LEGO Jurassic World: Legend of Isla Nublar\n")

    plot_parts_per_set(enriched, milestones, destination)

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