"""Diagramme de répartition des minifigs par genre."""

from pathlib import Path
from typing import List

import matplotlib.pyplot as plt

from lib.filesystem import ensure_parent_dir
from lib.plots.gender_palette import GENDER_COLORS, GENDER_LABELS
from lib.rebrickable.stats import read_rows


def load_gender_counts(path: Path) -> List[dict]:
    """Charge le CSV des comptes par genre."""
    return read_rows(path)


def plot_minifig_gender_share(counts_path: Path, destination_path: Path) -> None:
    """Trace un diagramme circulaire de la répartition des minifigs par genre."""
    rows = load_gender_counts(counts_path)
    if not rows:
        return
    genders = [row["gender"] for row in rows]
    counts = [int(row["minifig_count"]) for row in rows]
    colors = [GENDER_COLORS.get(gender.strip().lower(), GENDER_COLORS["unknown"]) for gender in genders]
    total = sum(counts)
    labels = []
    for gender, count in zip(genders, counts):
        percent = (count / total) * 100 if total else 0
        label = f"{GENDER_LABELS.get(gender.strip().lower(), 'Inconnu')} ({percent:.1f} %)"
        labels.append(label)

    fig, ax = plt.subplots(figsize=(6, 6))
    ax.pie(
        counts,
        labels=labels,
        colors=colors,
        startangle=90,
        wedgeprops={"linewidth": 0.6, "edgecolor": "#0d0d0d"},
    )
    centre_circle = plt.Circle((0, 0), 0.5, fc="white")
    ax.add_artist(centre_circle)
    ax.set_title("Répartition des minifigs par genre (thèmes filtrés)")

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