"""Graphique du nombre 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_counts(path: Path) -> List[dict]:
    """Charge le CSV des comptes de minifigs par set."""
    return read_rows(path)


def plot_minifigs_per_set(counts_path: Path, destination_path: Path) -> None:
    """Trace un diagramme en barres du nombre de minifigs par set (thèmes filtrés)."""
    rows = load_counts(counts_path)
    labels = [f"{row['set_num']} - {row['name']}" for row in rows]
    values = [int(row["minifig_count"]) for row in rows]
    positions = list(range(len(rows)))
    max_value = max(values)

    height = max(6, len(rows) * 0.18)
    fig, ax = plt.subplots(figsize=(14, height))
    bars = ax.barh(positions, values, color="#1f77b4", edgecolor="#0d0d0d", linewidth=0.6)
    ax.set_yticks(positions)
    ax.set_yticklabels(labels)
    ax.invert_yaxis()
    ax.set_xlabel("Nombre de minifigs")
    ax.set_title("Minifigs par set (thèmes filtrés)")
    ax.set_xlim(0, max_value + 0.8)
    ax.grid(True, axis="x", linestyle="--", alpha=0.25)
    for index, bar in enumerate(bars):
        value = values[index]
        ax.text(value + 0.2, bar.get_y() + bar.get_height() / 2, str(value), va="center", fontsize=8)

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