"""Filtrage des sets LEGO par identifiants de thèmes Rebrickable."""

import csv
from pathlib import Path
from typing import Dict, Iterable, List

from lib.filesystem import ensure_parent_dir

def parse_theme_ids(raw_value: str) -> List[str]:
    """Extrait les identifiants de thèmes depuis une chaîne séparée par des virgules."""
    values = [value.strip() for value in raw_value.split(",") if value.strip()]
    if not values:
        raise ValueError("Au moins un identifiant de thème est requis.")
    return values


def filter_sets_by_theme(
    source_path: Path,
    destination_path: Path,
    theme_ids: Iterable[str],
    overrides_path: Path,
) -> None:
    """Filtre le catalogue des sets en conservant uniquement les thèmes ciblés avec pièces."""
    ensure_parent_dir(destination_path)
    allowed_ids = set(theme_ids)
    overrides = load_num_parts_overrides(overrides_path)
    with source_path.open() as source_file, destination_path.open("w", newline="") as target_file:
        reader = csv.DictReader(source_file)
        writer = csv.DictWriter(target_file, fieldnames=reader.fieldnames)
        writer.writeheader()
        for row in reader:
            if row["theme_id"] in allowed_ids and int(row["num_parts"]) > 0:
                override = overrides.get(row["set_num"])
                writer.writerow({**row, "num_parts": override if override is not None else row["num_parts"]})


def load_num_parts_overrides(overrides_path: Path) -> Dict[str, str]:
    """Charge les corrections de nombre de pièces par set."""
    with overrides_path.open() as overrides_file:
        reader = csv.DictReader(overrides_file)
        return {row["set_num"]: row["num_parts"] for row in reader}
