"""Service d'export/import Excel pour la modification en masse de produits par point de vente."""

from dataclasses import dataclass, field
from decimal import Decimal, InvalidOperation
from io import BytesIO
import re
import unicodedata
import uuid

from django.db import IntegrityError, transaction

from dgi.models import ItemType, TaxGroup
from .models import Categorie, PointDeVente, Produit, ProduitPointVentePrix, StockPointDeVente
from .price_utils import (
    PRICE_SCOPE_GLOBAL,
    PRICE_SCOPE_PDV,
    appliquer_prix_produit,
    normalize_price_scope,
)


# ─── Définitions des colonnes ──────────────────────────────────────────────────

BULK_EDIT_COLUMNS_BASE = [
    {"field": "id_produit",   "header": "ID Produit",   "readonly": True,
     "description": "Identifiant interne. Ne pas modifier."},
    {"field": "code_sku",     "header": "Code produit", "readonly": False,
     "description": "Clé d'identification unique. Généré si vide lors d'une création."},
    {"field": "code_barres",  "header": "Code-barres",  "readonly": False,
     "description": "Code-barres unique (EAN-13, etc.). Optionnel."},
    {"field": "nom",          "header": "Nom",          "readonly": False,
     "description": "Nom commercial du produit. Obligatoire à la création."},
    {"field": "categorie",    "header": "Catégorie",    "readonly": False,
     "description": "Créée automatiquement si elle n'existe pas encore."},
    {"field": "typeart",      "header": "Type",         "readonly": False,
     "description": "Code type article DGI (ex : BIE, SER, TAX)."},
    {"field": "taxgroup",     "header": "Groupe taxe",  "readonly": False,
     "description": "Code groupe de taxe DGI (ex : A, B, C)."},
    {"field": "unite_mesure", "header": "Unité",        "readonly": False,
     "description": "Unité de mesure (ex : U, KG, L). Par défaut : U."},
    {"field": "prix_vente",   "header": "Prix Vente",   "readonly": False,
     "description": "Prix de vente."},
    {"field": "actif",        "header": "Statut",       "readonly": False,
     "description": "Actif ou Inactif. Laisser vide pour conserver la valeur existante."},
]

BULK_EDIT_COLUMNS_PDV_EXTRA = [
    {"field": "quantite",     "header": "Quantité",     "readonly": False,
     "description": "Quantité en stock pour ce point de vente."},
    {"field": "seuil_alerte", "header": "Seuil alerte", "readonly": False,
     "description": "Seuil d'alerte de réapprovisionnement."},
]

_FIELD_LABELS = {
    col["field"]: col["header"]
    for col in BULK_EDIT_COLUMNS_BASE + BULK_EDIT_COLUMNS_PDV_EXTRA
}

_HEADER_ALIASES = {
    "id produit":           "id_produit",
    "id":                   "id_produit",
    "identifiant":          "id_produit",
    "identifiant produit":  "id_produit",
    "code produit":         "code_sku",
    "code sku":             "code_sku",
    "code_sku":             "code_sku",
    "sku":                  "code_sku",
    "code":                 "code_sku",
    "code article":         "code_sku",
    "reference":            "code_sku",
    "ref":                  "code_sku",
    "code barres":          "code_barres",
    "code barre":           "code_barres",
    "code_barres":          "code_barres",
    "barcode":              "code_barres",
    "ean":                  "code_barres",
    "ean 13":               "code_barres",
    "nom":                  "nom",
    "nom produit":          "nom",
    "nom article":          "nom",
    "designation":          "nom",
    "libelle":              "nom",
    "categorie":            "categorie",
    "category":             "categorie",
    "famille":              "categorie",
    "type":                 "typeart",
    "type article":         "typeart",
    "typeart":              "typeart",
    "type produit":         "typeart",
    "groupe taxe":          "taxgroup",
    "groupe de taxe":       "taxgroup",
    "taxgroup":             "taxgroup",
    "taxe":                 "taxgroup",
    "tva":                  "taxgroup",
    "unite":                "unite_mesure",
    "unite mesure":         "unite_mesure",
    "unite de mesure":      "unite_mesure",
    "unit":                 "unite_mesure",
    "prix vente":           "prix_vente",
    "prix":                 "prix_vente",
    "prix unitaire":        "prix_vente",
    "prix de vente":        "prix_vente",
    "statut":               "actif",
    "actif":                "actif",
    "active":               "actif",
    "quantite":             "quantite",
    "quantite stock":       "quantite",
    "stock":                "quantite",
    "qty":                  "quantite",
    "seuil":                "seuil_alerte",
    "seuil alerte":         "seuil_alerte",
    "seuil d alerte":       "seuil_alerte",
    "alert":                "seuil_alerte",
}


# ─── Rapport ───────────────────────────────────────────────────────────────────

@dataclass
class BulkEditRowError:
    row_number: int
    messages: list
    code_produit: str = ""
    code_conditionnement: str = ""
    champ: str = ""


@dataclass
class BulkEditRowWarning:
    row_number: int
    messages: list


@dataclass
class BulkEditImportReport:
    created: int = 0
    updated: int = 0
    ignored: int = 0
    pending_updates: int = 0
    categories_created: int = 0
    skus_generated: int = 0
    barcode_collisions: int = 0
    total_rows: int = 0
    conditionnements_created: int = 0
    conditionnements_updated: int = 0
    errors: list = field(default_factory=list)
    warnings: list = field(default_factory=list)
    workbook_errors: list = field(default_factory=list)

    @property
    def has_errors(self):
        return bool(self.workbook_errors or self.errors)

    @property
    def has_pending_updates(self):
        return self.pending_updates > 0

    @property
    def rejected_rows(self):
        return len({error.row_number for error in self.errors})


# ─── Fonctions utilitaires ─────────────────────────────────────────────────────

class BulkEditExcelDependencyError(RuntimeError):
    """openpyxl non installé."""


def _load_openpyxl():
    try:
        from openpyxl import Workbook, load_workbook
        from openpyxl.styles import Font, PatternFill, Alignment
        from openpyxl.worksheet.datavalidation import DataValidation
        from openpyxl.utils import get_column_letter
    except ImportError as exc:
        raise BulkEditExcelDependencyError(
            "openpyxl n'est pas installé. Installez les dépendances du projet."
        ) from exc
    return Workbook, load_workbook, Font, PatternFill, Alignment, DataValidation, get_column_letter


def _normalize_text(value):
    """Normalise un texte : minuscule, sans accents, espaces unifiés."""
    text = unicodedata.normalize("NFD", str(value or "").strip().lower())
    text = "".join(ch for ch in text if unicodedata.category(ch) != "Mn")
    text = re.sub(r"[''`']+", " ", text)
    text = re.sub(r"[_\-]+", " ", text)
    text = re.sub(r"\([^)]*\)", " ", text)
    text = text.replace("*", " ")
    return re.sub(r"\s+", " ", text).strip()


def _clean_text(value):
    if value is None:
        return ""
    return re.sub(r"\s+", " ", str(value)).strip()


def _parse_decimal(value):
    if value is None:
        return None
    if isinstance(value, Decimal):
        return value
    text = str(value).strip()
    if not text:
        return None
    text = text.replace(" ", "").replace("\xa0", "")
    text = re.sub(r"[^\d,.\-]", "", text)
    text = text.replace(",", ".")
    try:
        return Decimal(text)
    except (InvalidOperation, ValueError):
        return None


def _parse_int(value):
    if value is None:
        return None
    try:
        return int(str(value).strip().split(".")[0])
    except (ValueError, AttributeError):
        return None


def _parse_bool_nullable(value):
    """Retourne True/False/None (None = non spécifié, conserver l'existant)."""
    if value is None or value == "":
        return None
    if isinstance(value, bool):
        return value
    normalized = _normalize_text(value)
    if normalized in {"1", "oui", "o", "yes", "y", "true", "vrai", "actif"}:
        return True
    if normalized in {"0", "non", "n", "no", "false", "faux", "inactif"}:
        return False
    return None


def _parse_id(value):
    if value is None or value == "":
        return None
    try:
        return int(str(value).strip().split(".")[0])
    except (ValueError, AttributeError):
        return None


def _is_empty_row(row):
    return all(_clean_text(cell) == "" for cell in row)


def _map_headers(header_row):
    columns = {}
    for index, header in enumerate(header_row):
        key = _normalize_text(header)
        field_name = _HEADER_ALIASES.get(key)
        if field_name and field_name not in columns:
            columns[field_name] = index
    return columns


def _get_cell(row, columns, field_name):
    col_index = columns.get(field_name)
    if col_index is None or col_index >= len(row):
        return None
    return row[col_index]


def _generate_unique_sku():
    """Génère un code SKU garanti absent de la base."""
    for _ in range(10):
        sku = f"GEN-{uuid.uuid4().hex[:8].upper()}"
        if not Produit.objects.filter(code_sku=sku).exists():
            return sku
    return f"GEN-{uuid.uuid4().hex[:12].upper()}"


def _normalize_sku(value):
    value = _clean_text(value)
    value = re.sub(r"\s+", "", value)
    return value.upper()


def _current_bulk_price(produit, pdv, portee_prix):
    if portee_prix != PRICE_SCOPE_PDV or pdv is None:
        return produit.prix_vente

    stock_price = (
        StockPointDeVente.objects.filter(produit=produit, point_de_vente=pdv)
        .exclude(prix_vente__isnull=True)
        .values_list("prix_vente", flat=True)
        .first()
    )
    if stock_price is not None:
        return stock_price

    pdv_price = (
        ProduitPointVentePrix.objects.filter(
            produit=produit,
            point_de_vente=pdv,
            conditionnement__facteur_conversion=Decimal("1"),
            actif=True,
        )
        .values_list("prix_vente", flat=True)
        .first()
    )
    return pdv_price if pdv_price is not None else produit.prix_vente


def _bulk_update_changes(
    produit,
    *,
    code_sku,
    new_barcode,
    apply_barcode,
    nom,
    categorie_name,
    typeart,
    taxgroup,
    unite_mesure,
    prix_vente,
    actif,
    quantite,
    seuil_alerte,
    pdv,
    portee_prix,
):
    """Retourne les champs qu'une ligne changerait sur un produit existant."""

    changes = []
    if code_sku and _normalize_sku(code_sku) != _normalize_sku(produit.code_sku):
        changes.append("code_sku")
    if apply_barcode and _clean_text(produit.code_barres) != (new_barcode or ""):
        changes.append("code_barres")
    if nom and _clean_text(produit.nom) != nom:
        changes.append("nom")
    if categorie_name:
        current_category = _normalize_text(produit.categorie.nom if produit.categorie else "")
        if current_category != _normalize_text(categorie_name):
            changes.append("categorie")
    if typeart and getattr(produit, "typeart_id", None) != typeart.pk:
        changes.append("typeart")
    if taxgroup and getattr(produit, "taxgroup_id", None) != taxgroup.pk:
        changes.append("taxgroup")
    if unite_mesure and _clean_text(produit.unite_mesure or "U").upper() != unite_mesure:
        changes.append("unite_mesure")
    if actif is not None and bool(produit.actif) != bool(actif):
        changes.append("actif")
    if prix_vente is not None and prix_vente > 0 and _current_bulk_price(produit, pdv, portee_prix) != prix_vente:
        changes.append("prix_vente")

    if pdv is not None:
        stock = StockPointDeVente.objects.filter(produit=produit, point_de_vente=pdv).first()
        if quantite is not None and quantite >= 0:
            if stock is None or stock.quantite != quantite:
                changes.append("quantite")
            if seuil_alerte is not None and seuil_alerte >= 0:
                current_threshold = stock.seuil_alerte if stock else 5
                if current_threshold != seuil_alerte:
                    changes.append("seuil_alerte")
        elif seuil_alerte is not None and seuil_alerte >= 0 and stock and stock.seuil_alerte != seuil_alerte:
            changes.append("seuil_alerte")

    return tuple(dict.fromkeys(changes))


def _format_bulk_update_confirmation_warning(code_sku, changes):
    labels = [_FIELD_LABELS.get(field_name, field_name) for field_name in changes]
    changed_fields = ", ".join(labels) if labels else "informations produit"
    return (
        f"Code produit « {code_sku} » deja present : champs differents detectes "
        f"({changed_fields}). Cochez la confirmation des mises a jour pour appliquer ces changements ; "
        "sinon la ligne reste intacte."
    )


# ─── Caches de référentiels ────────────────────────────────────────────────────

def _build_category_cache():
    cache = {}
    for cat in Categorie.objects.all().order_by("id"):
        key = _normalize_text(cat.nom)
        if key:
            cache.setdefault(key, cat)
    return cache


def _build_item_type_cache():
    from .product_excel import _build_item_type_cache as reference_cache
    return reference_cache()


def _build_tax_group_cache():
    from .product_excel import _build_tax_group_cache as reference_cache
    return reference_cache()


def _build_barcode_map():
    """Retourne {barcode: produit_id} pour tous les produits ayant un code-barres."""
    result = {}
    for row in (
        Produit.objects
        .exclude(code_barres__isnull=True)
        .exclude(code_barres="")
        .values("id", "code_barres")
    ):
        result[row["code_barres"]] = row["id"]
    return result


# ─── Colonnes selon le contexte ───────────────────────────────────────────────

def get_columns_for_context(pdv):
    """Retourne la liste de colonnes adaptée au contexte (global ou PDV spécifique)."""
    from .product_excel_conditionnements import COMBINED_COLUMN_SPECS
    return [{"field": "id_produit", "header": "ID Produit", "readonly": True, "description": "Identifiant interne en lecture seule."},
            {"field": "id_conditionnement", "header": "ID conditionnement", "readonly": True, "description": "Identifiant historique du conditionnement en lecture seule."}] + [dict(column, readonly=False) for column in COMBINED_COLUMN_SPECS]


# ─── Export ───────────────────────────────────────────────────────────────────

def build_bulk_edit_export_workbook(queryset, pdv=None, *, include_prices=True):
    """
    Construit le classeur Excel de modification en masse.

    Une ligne = Produit + Conditionnement ; deux feuilles, sans colonnes stock.
    pdv=None → prix catalogue du conditionnement.
    pdv=PDV  → prix local du conditionnement ou prix catalogue par défaut.
    """
    from .product_excel_conditionnements import build_combined_workbook
    return build_combined_workbook(products=queryset, pdv=pdv, modification=True, include_prices=include_prices)




def build_bulk_edit_template_workbook(pdv=None):
    """Construit un classeur vide (modèle) prêt à être rempli manuellement."""
    from .product_excel_conditionnements import build_combined_workbook
    return build_combined_workbook(modification=True)



def import_bulk_edit_from_excel(
    uploaded_file,
    *,
    pdv=None,
    created_by=None,
    portee_prix=PRICE_SCOPE_GLOBAL,
    commentaire_prix="",
    confirm_updates=False,
    can_create=True,
    can_update=True,
    can_create_conditionnements=True,
    can_update_conditionnements=True,
    can_edit_prices=True,
):
    """
    Importe les modifications depuis un classeur Excel.

    Nouveau format : codes produit/conditionnement, ID internes contrôlés,
    cellules vides conservées et transaction par groupe produit cohérent.
    Ancien format : identification ID → SKU → code-barres, savepoint par ligne
    et création d'un conditionnement unité. Les stocks ne sont jamais modifiés.
    """
    _, load_workbook, _, _, _, _, _ = _load_openpyxl()
    report = BulkEditImportReport()
    portee_prix = normalize_price_scope(portee_prix)

    try:
        workbook = load_workbook(uploaded_file, read_only=True, data_only=True)
    except Exception:
        report.workbook_errors.append("Le fichier Excel est illisible ou corrompu.")
        return report

    try:
        ws = workbook["Produits"] if "Produits" in workbook.sheetnames else workbook.active
        header_row = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
        if not header_row:
            report.workbook_errors.append("Aucune entête trouvée dans le fichier.")
            return report

        columns = _map_headers(header_row)
        from .product_excel_conditionnements import is_combined_sheet, import_combined_worksheet
        if is_combined_sheet(header_row):
            from .product_excel import ProductExcelImportReport
            return import_combined_worksheet(ws, ProductExcelImportReport(), modification=True,
                pdv=pdv, created_by=created_by, portee_prix=portee_prix,
                commentaire_prix=commentaire_prix, confirm_updates=confirm_updates,
                can_create=can_create, can_update=can_update,
                can_create_conditionnements=can_create_conditionnements,
                can_update_conditionnements=can_update_conditionnements, can_edit_prices=can_edit_prices)

        if "code_sku" not in columns and "id_produit" not in columns and "code_barres" not in columns:
            report.workbook_errors.append(
                "Aucune colonne d'identification trouvée "
                "(ID Produit, Code produit ou Code-barres)."
            )
            return report

        category_cache = _build_category_cache()
        item_type_cache = _build_item_type_cache()
        tax_group_cache = _build_tax_group_cache()
        barcode_map = _build_barcode_map()

        with transaction.atomic():
            for row_number, row in enumerate(
                ws.iter_rows(min_row=2, values_only=True), start=2
            ):
                if _is_empty_row(row):
                    report.ignored += 1
                    continue

                report.total_rows += 1
                sp = transaction.savepoint()
                row_errors = []
                row_warnings = []

                try:
                    _process_row(
                        row=row,
                        row_number=row_number,
                        columns=columns,
                        pdv=pdv,
                        created_by=created_by,
                        portee_prix=portee_prix,
                        commentaire_prix=commentaire_prix,
                        report=report,
                        row_errors=row_errors,
                        row_warnings=row_warnings,
                        category_cache=category_cache,
                        item_type_cache=item_type_cache,
                        tax_group_cache=tax_group_cache,
                        barcode_map=barcode_map,
                        confirm_updates=confirm_updates,
                        can_create=can_create, can_update=can_update,
                        can_create_conditionnements=can_create_conditionnements,
                        can_update_conditionnements=can_update_conditionnements,
                        can_edit_prices=can_edit_prices,
                    )
                except IntegrityError as exc:
                    transaction.savepoint_rollback(sp)
                    report.errors.append(BulkEditRowError(
                        row_number=row_number,
                        messages=[f"Erreur d'intégrité base de données : {exc}"],
                    ))
                    report.ignored += 1
                    continue
                except Exception as exc:
                    transaction.savepoint_rollback(sp)
                    report.errors.append(BulkEditRowError(
                        row_number=row_number,
                        messages=[f"Erreur inattendue : {exc}"],
                    ))
                    report.ignored += 1
                    continue

                if row_errors:
                    transaction.savepoint_rollback(sp)
                    report.errors.append(BulkEditRowError(
                        row_number=row_number, messages=row_errors
                    ))
                    report.ignored += 1
                else:
                    transaction.savepoint_commit(sp)
                    if row_warnings:
                        report.warnings.append(BulkEditRowWarning(
                            row_number=row_number, messages=row_warnings
                        ))
    finally:
        workbook.close()

    return report


def _process_row(
    row, row_number, columns, pdv, created_by, portee_prix, commentaire_prix, report,
    row_errors, row_warnings,
    category_cache, item_type_cache, tax_group_cache, barcode_map, confirm_updates=False,
    can_create=True, can_update=True, can_create_conditionnements=True, can_update_conditionnements=True, can_edit_prices=True,
):
    """Traite une ligne : identification, UPSERT catalogue, prix/stock PDV."""

    # Lecture des cellules
    raw_id        = _get_cell(row, columns, "id_produit")
    raw_sku       = _get_cell(row, columns, "code_sku")
    raw_barcode   = _get_cell(row, columns, "code_barres")
    raw_nom       = _get_cell(row, columns, "nom")
    raw_categorie = _get_cell(row, columns, "categorie")
    raw_typeart   = _get_cell(row, columns, "typeart")
    raw_taxgroup  = _get_cell(row, columns, "taxgroup")
    raw_unite     = _get_cell(row, columns, "unite_mesure")
    raw_prix      = _get_cell(row, columns, "prix_vente")
    raw_actif     = _get_cell(row, columns, "actif")
    raw_quantite  = _get_cell(row, columns, "quantite")
    raw_seuil     = _get_cell(row, columns, "seuil_alerte")

    # Parsing
    product_id     = _parse_id(raw_id)
    code_sku       = _normalize_sku(raw_sku) if _clean_text(raw_sku) else None
    new_barcode    = _clean_text(raw_barcode) or None
    nom            = _clean_text(raw_nom) or None
    categorie_name = _clean_text(raw_categorie) or None
    typeart_raw    = _clean_text(raw_typeart) or None
    taxgroup_raw   = _clean_text(raw_taxgroup) or None
    unite_mesure   = _clean_text(raw_unite).upper() or None
    prix_vente     = _parse_decimal(raw_prix)
    actif          = _parse_bool_nullable(raw_actif)
    quantite       = _parse_decimal(raw_quantite)
    seuil_alerte   = _parse_int(raw_seuil)
    if _clean_text(raw_quantite) or _clean_text(raw_seuil):
        row_warnings.append("Stock Excel ignoré : utilisez une réception ou un inventaire. Aucune écriture directe de stock.")
    quantite, seuil_alerte = None, None

    # Résolution type article et groupe taxe
    typeart = None
    if typeart_raw:
        typeart = item_type_cache.get(_normalize_text(typeart_raw))
        if not typeart:
            row_errors.append(f"Type article DGI « {typeart_raw} » introuvable ou inactif.")

    taxgroup = None
    if taxgroup_raw:
        taxgroup = tax_group_cache.get(_normalize_text(taxgroup_raw))
        if not taxgroup:
            row_errors.append(f"Groupe de taxation « {taxgroup_raw} » introuvable ou inactif.")

    # ── Identification du produit : le code produit est prioritaire ───────────
    produit = None

    if code_sku:
        produit = Produit.objects.filter(code_sku=code_sku).first()
        if product_id and produit and produit.pk != product_id:
            row_warnings.append(
                f"ID {product_id} ignoré : le code produit « {code_sku} » appartient au produit #{produit.pk}."
            )
    elif product_id:
        produit = Produit.objects.filter(pk=product_id).first()
        if not produit:
            row_warnings.append(
                f"ID {product_id} introuvable — tentative par code-barres."
            )

    if not produit and not code_sku and new_barcode:
        produit = Produit.objects.filter(code_barres=new_barcode).first()

    # ── Gestion collision code-barres ─────────────────────────────────────────
    apply_barcode = False
    if new_barcode:
        owner_id = barcode_map.get(new_barcode)
        if owner_id and (produit is None or owner_id != produit.pk):
            row_warnings.append(
                f"Code-barres « {new_barcode} » déjà utilisé par le produit #{owner_id} "
                f"— champ ignoré pour cette ligne."
            )
            report.barcode_collisions += 1
            new_barcode = None
        else:
            apply_barcode = True

    if produit:
        from .product_excel_conditionnements import unite_protegee
        if unite_mesure and _normalize_text(produit.unite_mesure) != _normalize_text(unite_mesure) and unite_protegee(produit):
            row_errors.append("L'unité de base est protégée : ce produit possède du stock ou un historique.")
        if not can_update:
            row_errors.append("Permission insuffisante pour modifier un produit.")
        if prix_vente is not None and prix_vente != _current_bulk_price(produit, pdv, portee_prix) and (not can_update_conditionnements or not can_edit_prices):
            row_errors.append("Permission insuffisante pour modifier les prix du conditionnement.")
    elif not can_create:
        row_errors.append("Permission insuffisante pour créer un produit.")
    if not produit and (not can_create_conditionnements or not can_edit_prices):
        row_errors.append("Permission insuffisante pour créer le conditionnement de base ou définir son prix.")
    if produit and not can_update_conditionnements and ((unite_mesure and unite_mesure != produit.unite_mesure) or (actif is not None and actif != produit.actif)):
        row_errors.append("Permission insuffisante pour modifier le conditionnement de base.")
    if row_errors:
        return

    if produit:
        pack_changes = produit.conditionnements.filter(facteur_conversion=1).count() if ((unite_mesure and unite_mesure != produit.unite_mesure) or (actif is not None and actif != produit.actif) or (prix_vente is not None and prix_vente != _current_bulk_price(produit, pdv, portee_prix))) else 0
        changes = _bulk_update_changes(
            produit,
            code_sku=code_sku,
            new_barcode=new_barcode,
            apply_barcode=apply_barcode,
            nom=nom,
            categorie_name=categorie_name,
            typeart=typeart,
            taxgroup=taxgroup,
            unite_mesure=unite_mesure,
            prix_vente=prix_vente,
            actif=actif,
            quantite=quantite,
            seuil_alerte=seuil_alerte,
            pdv=pdv,
            portee_prix=portee_prix,
        )
        if changes and not confirm_updates:
            report.pending_updates += 1
            report.ignored += 1
            row_warnings.append(_format_bulk_update_confirmation_warning(code_sku or produit.code_sku, changes))
            return

    # ── Catégorie (création auto) ──────────────────────────────────────────────
    categorie_obj = None
    if categorie_name:
        key = _normalize_text(categorie_name)
        categorie_obj = category_cache.get(key)
        if not categorie_obj:
            categorie_obj = Categorie.objects.create(nom=categorie_name)
            category_cache[key] = categorie_obj
            report.categories_created += 1
            row_warnings.append(f"Catégorie « {categorie_name} » créée automatiquement.")

    # ── MISE À JOUR ────────────────────────────────────────────────────────────
    if produit:
        update_fields = []

        if nom:
            produit.nom = nom
            update_fields.append("nom")

        if apply_barcode:
            produit.code_barres = new_barcode
            update_fields.append("code_barres")
            if new_barcode:
                barcode_map[new_barcode] = produit.pk

        # Changement de SKU : vérifier collision
        if code_sku and code_sku != produit.code_sku:
            conflict = Produit.objects.filter(code_sku=code_sku).exclude(pk=produit.pk).first()
            if conflict:
                row_warnings.append(
                    f"Code produit « {code_sku} » déjà pris par #{conflict.pk} — champ ignoré."
                )
            else:
                produit.code_sku = code_sku
                update_fields.append("code_sku")

        if categorie_obj:
            produit.categorie = categorie_obj
            update_fields.append("categorie")
        if typeart:
            produit.typeart = typeart
            update_fields.append("typeart")
        if taxgroup:
            produit.taxgroup = taxgroup
            update_fields.append("taxgroup")
        if unite_mesure:
            produit.unite_mesure = unite_mesure
            update_fields.append("unite_mesure")
        if actif is not None:
            produit.actif = actif
            update_fields.append("actif")

        if update_fields:
            produit.save(update_fields=update_fields)

        report.updated += 1
        report.conditionnements_updated += pack_changes

    # ── CRÉATION ──────────────────────────────────────────────────────────────
    else:
        if not nom:
            row_errors.append("Nom obligatoire pour créer un nouveau produit.")
            return

        if prix_vente is None or prix_vente < 0:
            row_errors.append("Prix de vente (>= 0) obligatoire pour créer un nouveau produit.")
            return

        if not code_sku:
            code_sku = _generate_unique_sku()
            row_warnings.append(f"Code produit généré automatiquement : {code_sku}")
            report.skus_generated += 1

        produit = Produit.objects.create(
            nom=nom,
            code_sku=code_sku,
            code_barres=new_barcode if apply_barcode else None,
            categorie=categorie_obj,
            typeart=typeart,
            taxgroup=taxgroup,
            prix_vente=prix_vente,
            unite_mesure=unite_mesure or "U",
            actif=True if actif is None else actif,
            created_by=created_by,
        )
        if new_barcode and apply_barcode:
            barcode_map[new_barcode] = produit.pk

        report.created += 1
        report.conditionnements_created += 1


    if prix_vente is not None and prix_vente > 0:
        appliquer_prix_produit(
            produit=produit,
            nouveau_prix=prix_vente,
            pdv=pdv,
            portee=portee_prix,
            commentaire=commentaire_prix,
            user=created_by,
            synchroniser_stock=False,
        )
