"""Tests des statistiques liées aux minifigs."""

from lib.rebrickable.minifig_stats import (
    MINIFIG_TOTAL_LABEL,
    TOTAL_PARTS_LABEL,
    compute_filtered_minifig_total,
    merge_minifig_stat,
)


def test_compute_filtered_minifig_total_counts_latest_inventory(tmp_path) -> None:
    """Additionne les minifigs en utilisant la dernière version d'inventaire."""
    inventories_path = tmp_path / "inventories.csv"
    inventories_path.write_text(
        "id,version,set_num\n"
        "1,1,123-1\n"
        "2,2,123-1\n"
        "3,1,124-1\n"
    )
    inventory_minifigs_path = tmp_path / "inventory_minifigs.csv"
    inventory_minifigs_path.write_text(
        "inventory_id,fig_num,quantity\n"
        "1,fig-01,1\n"
        "2,fig-02,3\n"
        "3,fig-03,2\n"
    )
    filtered_sets = [{"set_num": "123-1"}, {"set_num": "124-1"}]

    total = compute_filtered_minifig_total(filtered_sets, inventories_path, inventory_minifigs_path)

    assert total == 5


def test_merge_minifig_stat_inserts_after_total_parts_and_replaces_existing() -> None:
    """Insère l'entrée minifigs après le total de pièces et remplace l'ancienne valeur."""
    base_stats = [
        ("A", "1"),
        (TOTAL_PARTS_LABEL, "10"),
        ("B", "2"),
    ]

    with_minifigs = merge_minifig_stat(base_stats, 7)
    refreshed = merge_minifig_stat(with_minifigs, 8)

    assert with_minifigs == [
        ("A", "1"),
        (TOTAL_PARTS_LABEL, "10"),
        (MINIFIG_TOTAL_LABEL, "7"),
        ("B", "2"),
    ]
    assert refreshed == [
        ("A", "1"),
        (TOTAL_PARTS_LABEL, "10"),
        (MINIFIG_TOTAL_LABEL, "8"),
        ("B", "2"),
    ]
