"""Tests des statistiques simples sur les pièces filtrées."""

import csv
from pathlib import Path

from lib.rebrickable.parts_stats import build_stats, read_rows, write_parts_stats


def write_csv(path: Path, headers: list[str], rows: list[list[str]]) -> None:
    """Écrit un CSV simple pour les besoins de tests."""
    with path.open("w", newline="") as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(headers)
        writer.writerows(rows)


def test_build_stats(tmp_path: Path) -> None:
    """Calcule les statistiques principales sans les pièces de rechange."""
    parts_path = tmp_path / "parts_filtered.csv"
    sets_path = tmp_path / "sets_enriched.csv"
    stats_path = tmp_path / "stats.csv"
    write_csv(
        parts_path,
        ["part_num", "color_rgb", "is_translucent", "set_num", "set_id", "quantity_in_set", "is_spare"],
        [
            ["3001", "FFFFFF", "false", "1000-1", "1000", "2", "false"],
            ["3001", "FFFFFF", "false", "2000-1", "2000", "1", "false"],
            ["3002", "000000", "true", "1000-1", "1000", "5", "false"],
            ["3003", "FF0000", "false", "1000-1", "1000", "1", "true"],
        ],
    )
    write_csv(
        sets_path,
        ["set_num", "set_id", "num_parts", "in_collection"],
        [
            ["1000-1", "1000", "8", "true"],
            ["2000-1", "2000", "1", "false"],
        ],
    )
    write_csv(
        stats_path,
        ["libelle", "valeur"],
        [
            ["Total de pièces pour les thèmes filtrés", "9"],
        ],
    )

    stats = build_stats(read_rows(parts_path), sets_path, parts_path, stats_path)

    assert stats == [
        ("Total de variations de pièces (hors rechanges)", "2"),
        (
            "Pièce la moins utilisée (référence + couleur)",
            "3001 / FFFFFF / false (3)",
        ),
        (
            "Pièce la plus commune (référence + couleur)",
            "3002 / 000000 / true (5)",
        ),
        ("Total de couleurs utilisées (hors rechanges)", "2"),
        ("Total de pièces hors rechanges", "8"),
        ("Ecart total catalogue (stats) - inventaire (hors rechanges)", "1"),
        ("Nombre de sets en écart inventaire/catalogue", "0"),
        ("Ecart maximal inventaire/catalogue", "none (0)"),
    ]


def test_write_parts_stats(tmp_path: Path) -> None:
    """Écrit un CSV de statistiques."""
    destination_path = tmp_path / "parts_stats.csv"
    stats = [
        ("A", "1"),
        ("B", "2"),
    ]

    write_parts_stats(destination_path, stats)

    with destination_path.open() as csv_file:
        rows = list(csv.reader(csv_file))

    assert rows == [
        ["libelle", "valeur"],
        ["A", "1"],
        ["B", "2"],
    ]
