#!/usr/bin/env python3
"""
Compte les produits « parents » à importer (hors variantes)
à partir de ../files/Products/ProductsOutput.csv
"""

import csv
import sys
import os
from pathlib import Path

# (facultatif) si ton projet importe des modules internes
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))

# Chemin du CSV – relatif à ce fichier Python
file_path_csv: Path = Path(__file__).parent / "../files/Products/ProductsOutput.csv"

DELIMITER = ';'
ENCODING  = 'ISO-8859-1'


def safe(val: str | None) -> str:
    """Renvoie une chaîne non-nulle, sans espaces superflus."""
    return (val or "").strip()


def count_parent_products(csv_path: Path) -> int:
    """
    Renvoie le nombre de produits parent à importer
    (Statut = "O", Nature = "PV 2025 OK", Code article commençant par "00").
    Une fiche parent = 1, ses variantes = 0.
    """
    with csv_path.open('r', encoding=ENCODING, newline='') as fh:
        reader = csv.DictReader(fh, delimiter=DELIMITER)

        required_headers = {"Code article", "Actif", "Nature", "Produit Parent"}
        if not required_headers.issubset(reader.fieldnames or []):
            missing = required_headers - set(reader.fieldnames or [])
            raise ValueError(f"En-têtes manquantes dans le CSV : {', '.join(missing)}")

        products = set()

        for row in reader:
            actif       = safe(row.get("Actif"))
            nature      = safe(row.get("Nature"))
            code_article = safe(row.get("Code article"))

            # 1) Filtre
            if actif != "O":
                continue
            if nature != "PV 2025 OK":
                continue
            if not code_article:          # ligne incomplète
                continue

            # 2) Clé unique : parent si présent, sinon code-article
            parent = safe(row.get("Produit Parent"))
            key = parent if parent else code_article
            products.add(key)

    return len(products)


if __name__ == "__main__":
    try:
        total = count_parent_products(file_path_csv)
        print(f"Nombre de produits à importer (hors variantes) : {total}")
    except FileNotFoundError:
        print(f"Fichier introuvable : {file_path_csv.resolve()}")
    except Exception as exc:
        print(f"Erreur : {exc}")
