"""Tests de la visualisation des couleurs utilisées."""

from pathlib import Path

import matplotlib

from lib.plots.colors_grid import build_hex_positions, load_used_colors, plot_colors_grid


matplotlib.use("Agg")


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

        writer = csv.writer(csv_file)
        writer.writerow(headers)
        writer.writerows(rows)


def test_build_hex_positions() -> None:
    """Construit suffisamment de positions pour toutes les couleurs."""
    positions = build_hex_positions(10, columns=4, spacing=1.0)
    assert len(positions) == 10
    assert positions[0] == (0.0, 0.0)
    assert positions[1][0] > positions[0][0]


def test_plot_colors_grid(tmp_path: Path) -> None:
    """Produit un fichier image avec les couleurs utilisées."""
    parts_path = tmp_path / "parts_filtered.csv"
    colors_path = tmp_path / "colors.csv"
    parts_catalog_path = tmp_path / "parts.csv"
    destination_path = tmp_path / "colors_grid.png"

    write_csv(
        parts_path,
        ["part_num", "color_rgb", "is_translucent", "set_id", "quantity_in_set", "is_spare"],
        [
            ["3001", "FFFFFF", "false", "1000", "2", "false"],
            ["3002", "000000", "true", "1000", "5", "false"],
            ["3003", "FF0000", "false", "1000", "1", "true"],
            ["3004", "0033B2", "false", "1000", "10", "false"],
        ],
    )
    write_csv(
        parts_catalog_path,
        ["part_num", "name", "part_cat_id"],
        [
            ["3001", "Brick", "11"],
            ["3002", "Pane", "23"],
            ["3003", "Slope", "3"],
            ["3004", "Technic", "8"],
        ],
    )
    write_csv(
        colors_path,
        ["id", "name", "rgb", "is_trans", "num_parts", "num_sets", "y1", "y2"],
        [
            ["1", "White", "FFFFFF", "False", "0", "0", "0", "0"],
            ["2", "Black", "000000", "True", "0", "0", "0", "0"],
            ["3", "Red", "FF0000", "False", "0", "0", "0", "0"],
            ["4", "Ignored Blue", "0033B2", "False", "0", "0", "0", "0"],
        ],
    )

    colors = load_used_colors(parts_path, colors_path, parts_catalog_path)
    assert len(colors) == 2

    plot_colors_grid(parts_path, colors_path, parts_catalog_path, destination_path)

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