"""Tests de l'enrichissement des sets filtrés."""

from pathlib import Path

from lib.rebrickable.enrich_sets import (
    build_rebrickable_set_url,
    enrich_sets,
    extract_set_id,
    load_owned_set_ids,
    parse_set_collection_root,
    write_missing_sets_markdown,
)


def test_extract_set_id_removes_revision() -> None:
    """Supprime la révision de l'identifiant set_num."""
    assert extract_set_id("75936-1") == "75936"


def test_build_rebrickable_set_url() -> None:
    """Construit l'URL publique Rebrickable à partir du set_num."""
    assert build_rebrickable_set_url("75936-1") == "https://rebrickable.com/sets/75936-1"


def test_parse_set_collection_root_empty_returns_none() -> None:
    """Renvoie None pour une valeur vide."""
    assert parse_set_collection_root("   ") is None


def test_load_owned_set_ids_handles_missing_and_collects(tmp_path: Path) -> None:
    """Retourne les sets présents sous forme de dossiers, vide si rien n'existe."""
    missing_root = tmp_path / "absent"
    assert load_owned_set_ids(missing_root) == set()

    root = tmp_path / "collection"
    root.mkdir()
    (root / "75936").mkdir()
    (root / "75944").mkdir()
    assert load_owned_set_ids(root) == {"75936", "75944"}


def test_enrich_sets_adds_columns_and_collection(tmp_path: Path) -> None:
    """Enrichit le CSV avec set_id, URL et possession."""
    source = tmp_path / "sets_filtered.csv"
    destination = tmp_path / "sets_enriched.csv"
    source.write_text(
        "set_num,name,year,theme_id\n"
        "75936-1,T. rex Rampage,2019,602\n"
        "10757-1,Raptor Rescue Truck,2018,620\n"
    )

    enrich_sets(source, destination, {"75936"})

    assert destination.read_text() == (
        "set_num,name,year,theme_id,set_id,rebrickable_url,in_collection\n"
        "75936-1,T. rex Rampage,2019,602,75936,https://rebrickable.com/sets/75936-1,true\n"
        "10757-1,Raptor Rescue Truck,2018,620,10757,https://rebrickable.com/sets/10757-1,false\n"
    )


def test_write_missing_sets_markdown(tmp_path: Path) -> None:
    """Construit un tableau Markdown des sets non possédés."""
    enriched = tmp_path / "sets_enriched.csv"
    markdown = tmp_path / "sets_missing.md"
    enriched.write_text(
        "set_num,name,year,theme_id,set_id,rebrickable_url,in_collection\n"
        "75936-1,T. rex Rampage,2019,602,75936,https://rebrickable.com/sets/75936-1,true\n"
        "10757-1,Raptor Rescue Truck,2018,620,10757,https://rebrickable.com/sets/10757-1,false\n"
    )

    write_missing_sets_markdown(enriched, markdown)

    assert markdown.read_text() == (
        "| set_id | year | name |\n"
        "| --- | --- | --- |\n"
        "| [10757](https://rebrickable.com/sets/10757-1) | 2018 | Raptor Rescue Truck |\n"
    )
