"""Services d'import/export Excel pour le catalogue produits."""

from dataclasses import dataclass, field
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from io import BytesIO
from pathlib import Path
import re
import unicodedata

from django.db import transaction
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy, gettext as _

from dgi.models import ItemType, TaxGroup

from .models import (
    Categorie,
    ConditionnementProduit,
    PointDeVente,
    Produit,
    ProduitPointVentePrix,
    StockPointDeVente,
)


PRODUCT_EXCEL_COLUMN_SPECS = (
    {
        "field": "code_sku",
        "header": gettext_lazy("Code produit"),
        "required": True,
        "description": gettext_lazy("Identifiant unique du produit."),
    },
    {
        "field": "nom",
        "header": gettext_lazy("Nom *"),
        "required": True,
        "description": gettext_lazy("Nom commercial du produit."),
    },
    {
        "field": "typeart",
        "header": gettext_lazy("Type article DGI *"),
        "required": True,
        "description": gettext_lazy("Obligatoire. Code ou nom d'un type article DGI actif existant."),
    },
    {
        "field": "categorie",
        "header": gettext_lazy("Categorie"),
        "required": False,
        "description": gettext_lazy("Categorie creee automatiquement si elle n'existe pas."),
    },
    {
        "field": "prix_vente",
        "header": gettext_lazy("Prix Vente"),
        "required": False,
        "description": gettext_lazy("Ancien format compatible : prix du conditionnement de base facteur 1."),
    },
    {
        "field": "unite_mesure",
        "header": gettext_lazy("Unite de base"),
        "required": False,
        "description": gettext_lazy("Exemples : U, KG, L. Valeur par defaut : U."),
    },
    {
        "field": "taxgroup",
        "header": gettext_lazy("Groupe de taxation *"),
        "required": True,
        "description": gettext_lazy("Obligatoire. Code ou nom d'un groupe de taxation DGI actif existant."),
    },
    {
        "field": "actif",
        "header": gettext_lazy("Actif (Oui/Non)"),
        "required": False,
        "description": gettext_lazy("Valeurs acceptees : Oui ou Non. Valeur par defaut : Oui."),
    },
)

PRODUCT_EXCEL_HEADERS = tuple(column["header"] for column in PRODUCT_EXCEL_COLUMN_SPECS)
PRODUCT_EXCEL_EXPORT_FIELDS = tuple(column["field"] for column in PRODUCT_EXCEL_COLUMN_SPECS)

PRODUCT_EXCEL_SAMPLE_ROW = (
    "SKU-001",
    "Exemple Produit",
    "BIE",
    "Catégorie Exemple",
    10,
    "U",
    "B",
    "Oui",
)

REQUIRED_IMPORT_FIELDS = ("code_sku", "nom", "typeart", "taxgroup")

HEADER_ALIASES = {
    "nom": "nom",
    "nom produit": "nom",
    "nom article": "nom",
    "produit": "nom",
    "produit nom": "nom",
    "article": "nom",
    "designation": "nom",
    "libelle": "nom",
    "description produit": "nom",
    "product name": "nom",
    "name": "nom",
    "code sku": "code_sku",
    "code produit": "code_sku",
    "codeproduit": "code_sku",
    "code_sku": "code_sku",
    "code article": "code_sku",
    "reference": "code_sku",
    "ref": "code_sku",
    "sku": "code_sku",
    "product code": "code_sku",
    "type article": "typeart",
    "type article dgi": "typeart",
    "typeart": "typeart",
    "type d article": "typeart",
    "type produit": "typeart",
    "item type": "typeart",
    "groupe taxe": "taxgroup",
    "groupe de taxe": "taxgroup",
    "groupe de taxation": "taxgroup",
    "taxgroup": "taxgroup",
    "tax group": "taxgroup",
    "taxe": "taxgroup",
    "tva": "taxgroup",
    "categorie": "categorie",
    "cat\ufffdgorie": "categorie",
    "category": "categorie",
    "famille": "categorie",
    "prix par defaut": "prix_vente",
    "prix achat": "prix_vente",
    "prix d achat": "prix_vente",
    "prix unitaire": "prix_vente",
    "prix unitaire achat": "prix_vente",
    "prix unitaire d achat": "prix_vente",
    "prix de revient": "prix_vente",
    "cout achat": "prix_vente",
    "cout d achat": "prix_vente",
    "prix de vente": "prix_vente",
    "prix vente": "prix_vente",
    "prix vente usd": "prix_vente",
    "prix": "prix_vente",
    "sale price": "prix_vente",
    "selling price": "prix_vente",
    "sale price usd": "prix_vente",
    "unit price": "prix_vente",
    "price": "prix_vente",
    "unite de mesure": "unite_mesure",
    "unite mesure": "unite_mesure",
    "unite": "unite_mesure",
    "unit": "unite_mesure",
    "unit of measure": "unite_mesure",
    "uom": "unite_mesure",
    "image": "image",
    "image produit": "image",
    "point de vente": "point_de_vente",
    "pdv": "point_de_vente",
    "prix point de vente": "prix_point_de_vente",
    "prix pdv": "prix_point_de_vente",
    "prix vente pdv": "prix_point_de_vente",
    "prix de vente pdv": "prix_point_de_vente",
    "prix vente point de vente": "prix_point_de_vente",
    "prix de vente point de vente": "prix_point_de_vente",
    "stock point de vente": "stock_point_de_vente",
    "stock pdv": "stock_point_de_vente",
    "stock": "stock_point_de_vente",
    "quantite": "stock_point_de_vente",
    "quantite actuelle": "stock_point_de_vente",
    "stock initial": "stock_point_de_vente",
    "actif": "actif",
    "active": "actif",
    "taxe specifique active": "taxe_specifique_active",
    "active taxe specifique": "taxe_specifique_active",
    "soumis a une taxe specifique": "est_taxe_specifique",
    "taxe specifique": "est_taxe_specifique",
    "est taxe specifique": "est_taxe_specifique",
    "taxe specifique valeur": "taxe_specifique_valeur",
    "valeur taxe specifique": "taxe_specifique_valeur",
    "description taxe specifique": "taxe_specifique_description",
    "taxe specifique description": "taxe_specifique_description",
}

FIELD_LABELS = {
    **{column["field"]: column["header"] for column in PRODUCT_EXCEL_COLUMN_SPECS},
    "image": gettext_lazy("Image"),
    "point_de_vente": gettext_lazy("Point de vente"),
    "prix_point_de_vente": gettext_lazy("Prix point de vente"),
    "stock_point_de_vente": gettext_lazy("Stock point de vente"),
    "taxe_specifique_active": gettext_lazy("Taxe specifique active"),
    "est_taxe_specifique": gettext_lazy("Soumis a une taxe specifique"),
    "taxe_specifique_valeur": gettext_lazy("Taxe specifique valeur"),
    "taxe_specifique_description": gettext_lazy("Description taxe specifique"),
}

CONDITIONNEMENT_EXCEL_HEADERS = (
    gettext_lazy("Code produit"),
    gettext_lazy("Code conditionnement"),
    gettext_lazy("Libelle"),
    gettext_lazy("Facteur"),
    gettext_lazy("Prix de vente"),
    gettext_lazy("Vendable"),
    gettext_lazy("Achetable"),
    gettext_lazy("Par defaut"),
    gettext_lazy("Fractionnable"),
    gettext_lazy("Actif"),
)

CONDITIONNEMENT_SAMPLE_ROW = (
    "SKU-001",
    "SKU-001-CARTON24",
    "Carton de 24",
    24,
    20000,
    "Oui",
    "Oui",
    "Non",
    "Non",
    "Oui",
)

PRODUCT_MODEL_UPDATE_FIELDS = {
    "nom",
    "code_sku",
    "categorie",
    "typeart",
    "taxgroup",
    "prix_vente",
    "unite_mesure",
    "image",
    "actif",
    "est_taxe_specifique",
    "taxe_specifique_active",
    "taxe_specifique_valeur",
    "taxe_specifique_description",
}


class ProductExcelDependencyError(RuntimeError):
    """Erreur explicite quand openpyxl n'est pas installe dans l'environnement."""


PRODUCT_IMPORT_TEMPLATE_PATH = (
    Path(__file__).resolve().parent
    / "resources"
    / "modele_import_produits_FacControl.xlsx"
)


def load_products_import_template_workbook():
    """Retourne sans transformation le modèle Excel validé de FacControl."""

    try:
        return PRODUCT_IMPORT_TEMPLATE_PATH.read_bytes()
    except OSError as exc:
        raise ProductExcelDependencyError(
            "Le modèle Excel d'import produits est indisponible."
        ) from exc


@dataclass
class ProductExcelRowError:
    """Erreur rattachee a une ligne precise du fichier Excel."""

    row_number: int
    messages: list[str]
    sheet_name: str = "Produits"
    code_produit: str = ""
    code_conditionnement: str = ""
    champ: str = ""
    field_label: str = ""


@dataclass
class ProductExcelRowWarning:
    """Avertissement non bloquant rattache a une ligne du fichier Excel."""

    row_number: int
    messages: list[str]
    sheet_name: str = "Produits"
    code_produit: str = ""
    code_conditionnement: str = ""
    champ: str = ""


@dataclass
class ProductExcelImportReport:
    """Rapport lisible apres traitement d'un import produits."""

    created: int = 0
    updated: int = 0
    unchanged_products: int = 0
    ignored: int = 0
    pending_updates: int = 0
    categories_created: int = 0
    point_prices_created: int = 0
    point_prices_updated: int = 0
    stocks_updated: int = 0
    conditionnements_created: int = 0
    conditionnements_updated: int = 0
    rejected_rows: int = 0
    conditionnements_ignored: int = 0
    total_rows: int = 0
    errors: list[ProductExcelRowError] = field(default_factory=list)
    warnings: list[ProductExcelRowWarning] = field(default_factory=list)
    workbook_errors: list[str] = field(default_factory=list)
    imported_product_ids: set[int] = field(default_factory=set)

    @property
    def has_errors(self):
        """Indique si le fichier contenait des erreurs bloquantes ou de ligne."""

        return bool(self.workbook_errors or self.errors)

    @property
    def has_pending_updates(self):
        """Indique si des produits existants attendent une confirmation utilisateur."""

        return self.pending_updates > 0


@dataclass
class _ValidatedProductRow:
    """Ligne valide prete a etre appliquee en base."""

    row_number: int
    nom: str
    code_sku: str
    normalized_sku: str
    categorie: str
    typeart: ItemType | None
    taxgroup: TaxGroup | None
    prix_vente: Decimal
    unite_mesure: str
    image_path: str
    actif: bool
    est_taxe_specifique: bool
    taxe_specifique_active: bool
    taxe_specifique_valeur: str
    taxe_specifique_description: str
    existing_product: Produit | None
    point_de_vente: PointDeVente | None = None
    points_de_vente: tuple[PointDeVente, ...] = ()
    prix_point_de_vente: Decimal | None = None
    stock_point_de_vente: Decimal | None = None
    ensure_stock_point_de_vente: bool = False


def _load_openpyxl():
    """Charge openpyxl uniquement quand une action Excel est executee."""

    try:
        from openpyxl import Workbook, load_workbook
        from openpyxl.styles import Font, PatternFill
        from openpyxl.worksheet.datavalidation import DataValidation
    except ImportError as exc:
        raise ProductExcelDependencyError(
            "La bibliotheque openpyxl n'est pas installee. "
            "Installez les dependances du projet puis reessayez."
        ) from exc

    return Workbook, load_workbook, Font, PatternFill, DataValidation


def _normalize_lookup_text(value):
    """Normalise un texte pour les comparaisons souples."""

    text = unicodedata.normalize("NFD", str(value or "").strip().lower())
    text = "".join(char for char in text if unicodedata.category(char) != "Mn")
    text = re.sub(r"['’`]+", " ", text)
    text = re.sub(r"[_\-]+", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def _normalize_header_text(value):
    """Normalise un libelle Excel en ignorant les indications visuelles."""

    text = _normalize_lookup_text(value)
    text = re.sub(r"\([^)]*\)", " ", text)
    text = text.replace("*", " ")
    return re.sub(r"\s+", " ", text).strip()


def _normalize_product_name(value):
    """Normalise le nom produit comme le formulaire de saisie manuel."""

    value = str(value or "").strip()
    value = re.sub(r"\s+", " ", value)
    return value.casefold()


def _clean_text(value):
    """Nettoie une valeur texte issue d'une cellule Excel."""

    if value is None:
        return ""
    if isinstance(value, str):
        return re.sub(r"\s+", " ", value).strip()
    return re.sub(r"\s+", " ", str(value)).strip()


def _normalize_sku(value):
    """Normalise un code produit pour detecter les doublons sans toucher aux calculs metier."""

    value = _clean_text(value)
    value = re.sub(r"\s+", "", value)
    return value.upper()


def _parse_decimal(value):
    """Convertit proprement les prix saisis dans Excel."""

    if value is None:
        return None
    if isinstance(value, Decimal):
        return value
    text = str(value).strip()
    if not text:
        return None
    text = text.replace("\u00a0", " ").replace(" ", "")
    text = text.replace("$", "").replace("USD", "").replace("FC", "").replace("CDF", "")
    text = text.replace(",", ".")
    try:
        return Decimal(text)
    except (InvalidOperation, ValueError):
        return None


def _round_import_decimal(value, decimal_places):
    """Adapte les décimales Excel à la précision du champ, après contrôle du signe."""

    try:
        return value.quantize(Decimal(1).scaleb(-decimal_places), rounding=ROUND_HALF_UP)
    except InvalidOperation:
        # Les valeurs trop grandes restent soumises aux limites du DecimalField.
        return value


def _parse_bool(value, default=False):
    """Interprete les valeurs booleennes frequentes dans un fichier Excel."""

    if value is None or value == "":
        return default
    if isinstance(value, bool):
        return value
    if isinstance(value, (int, float, Decimal)):
        return bool(value)

    normalized = _normalize_lookup_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 default


def _parse_bool_strict(value, *, default=None):
    """Retourne (valeur, valide) afin de rejeter les booleens ambigus."""

    if value is None or str(value).strip() == "":
        return default, True
    if isinstance(value, bool):
        return value, True
    if isinstance(value, (int, float, Decimal)) and value in (0, 1):
        return bool(value), True
    normalized = _normalize_lookup_text(value)
    if normalized in {"1", "oui", "o", "yes", "y", "true", "vrai", "actif"}:
        return True, True
    if normalized in {"0", "non", "n", "no", "false", "faux", "inactif"}:
        return False, True
    return default, False


def _is_empty_row(row):
    """Repere les lignes completement vides a ignorer sans erreur."""

    return all(_clean_text(cell) == "" for cell in row)


def _is_template_sample_row(row, columns):
    """Detecte la ligne exemple du modele telecharge pour ne pas l'importer."""

    sample_by_field = dict(zip(PRODUCT_EXCEL_EXPORT_FIELDS, PRODUCT_EXCEL_SAMPLE_ROW))
    for field_name, sample_value in sample_by_field.items():
        row_value = _get_row_value(row, columns, field_name)
        if _normalize_lookup_text(row_value) != _normalize_lookup_text(sample_value):
            return False
    return True


def _map_headers(header_row):
    """Associe les entetes Excel aux champs attendus par l'import."""

    columns = {}
    for index, header in enumerate(header_row):
        normalized_header = _normalize_header_text(header)
        field_name = HEADER_ALIASES.get(normalized_header)
        if field_name and field_name not in columns:
            columns[field_name] = index
    return columns


def _get_row_value(row, columns, field_name):
    """Recupere une cellule par nom de champ avec tolerance sur les colonnes absentes."""

    column_index = columns.get(field_name)
    if column_index is None or column_index >= len(row):
        return None
    return row[column_index]


def _conditionnement_columns(header_row):
    """Mappe strictement les colonnes de la feuille Conditionnements."""

    aliases = {
        "code produit": "code_sku",
        "code conditionnement": "code",
        "libelle": "libelle",
        "facteur": "facteur_conversion",
        "facteur de conversion": "facteur_conversion",
        "prix de vente": "prix_vente",
        "prix vente": "prix_vente",
        "vendable": "vendable",
        "achetable": "achetable",
        "par defaut": "par_defaut",
        "fractionnable": "fractionnable",
        "actif": "actif",
    }
    columns = {}
    for index, header in enumerate(header_row):
        field_name = aliases.get(_normalize_header_text(header))
        if field_name and field_name not in columns:
            columns[field_name] = index
    return columns


def _normalize_export_fields(selected_fields=None):
    """Retourne les colonnes exportables dans l'ordre du modele."""

    allowed_fields = set(PRODUCT_EXCEL_EXPORT_FIELDS)
    selected = [field for field in (selected_fields or PRODUCT_EXCEL_EXPORT_FIELDS) if field in allowed_fields]
    if not selected:
        selected = list(PRODUCT_EXCEL_EXPORT_FIELDS)
    return [field for field in PRODUCT_EXCEL_EXPORT_FIELDS if field in selected]


def _get_export_cell_value(produit, field_name):
    """Transforme un produit en valeur cellule selon la colonne demandee."""

    if field_name == "code_sku":
        return produit.code_sku
    if field_name == "nom":
        return produit.nom
    if field_name == "typeart":
        return getattr(produit.typeart, "code", "") if produit.typeart else ""
    if field_name == "categorie":
        return produit.categorie.nom if produit.categorie else ""
    if field_name == "prix_vente":
        return produit.prix_vente
    if field_name == "unite_mesure":
        return produit.unite_mesure or "U"
    if field_name == "taxgroup":
        return getattr(produit.taxgroup, "display_label", "") if produit.taxgroup else ""
    if field_name == "actif":
        return "Oui" if produit.actif else "Non"
    return ""


def _build_existing_product_maps():
    """Prepare les caches produits pour eviter une requete par ligne importee."""

    products_by_sku = {}
    queryset = Produit.objects.select_related("categorie").all().order_by("id")
    for produit in queryset.iterator(chunk_size=1000):
        normalized_sku = _normalize_sku(produit.code_sku)
        if normalized_sku:
            products_by_sku.setdefault(normalized_sku, produit)
    return products_by_sku


def _build_category_cache():
    """Prepare un cache des categories existantes, insensible aux accents et a la casse."""

    categories = {}
    for category in Categorie.objects.all().order_by("id").iterator(chunk_size=1000):
        normalized_name = _normalize_lookup_text(category.nom)
        if normalized_name:
            categories.setdefault(normalized_name, category)
    return categories


def _build_reference_cache(model):
    """Prepare un cache code/nom pour les references DGI existantes."""

    references = {}
    queryset = model.objects.all()
    if any(field.name == "is_active" for field in model._meta.fields):
        queryset = queryset.filter(is_active=True)
    for reference in queryset.order_by("id").iterator(chunk_size=1000):
        for value in (
            getattr(reference, "code", ""),
            getattr(reference, "name", ""),
            str(reference),
        ):
            normalized_value = _normalize_lookup_text(value)
            if normalized_value:
                references.setdefault(normalized_value, reference)
    return references


def _build_item_type_cache():
    """Prepare un cache tolerant pour les types d'article frequents."""

    references = _build_reference_cache(ItemType)
    by_code = {
        str(item_type.code or "").strip().upper(): item_type
        for item_type in ItemType.objects.filter(is_active=True)
    }
    aliases = {
        "bien": "BIE",
        "biens": "BIE",
        "good": "BIE",
        "goods": "BIE",
        "produit": "BIE",
        "produits": "BIE",
        "marchandise": "BIE",
        "marchandises": "BIE",
        "service": "SER",
        "services": "SER",
        "taxe": "TAX",
        "taxes": "TAX",
        "tax": "TAX",
    }
    for alias, code in aliases.items():
        reference = by_code.get(code)
        if reference:
            references.setdefault(_normalize_lookup_text(alias), reference)
    return references


def _build_tax_group_cache():
    """Prepare un cache tolerant pour les groupes de taxe usuels."""

    references = _build_reference_cache(TaxGroup)
    by_code = {
        str(tax_group.code or "").strip().upper(): tax_group
        for tax_group in TaxGroup.objects.filter(is_active=True)
    }
    aliases = {
        "exonere": "A",
        "exonere et hors champ": "A",
        "hors champ": "S",
        "taxable 16": "B",
        "taxable 16%": "B",
        "tva 16": "B",
        "tva 16%": "B",
        "taxable 5": "C",
        "taxable 5%": "C",
        "tva 5": "C",
        "tva 5%": "C",
        "taxable 1": "O",
        "taxable 1%": "O",
        "tva 1": "O",
        "tva 1%": "O",
        "taxable 8": "Q",
        "taxable 8%": "Q",
        "tva 8": "Q",
        "tva 8%": "Q",
    }
    for alias, code in aliases.items():
        reference = by_code.get(code)
        if reference:
            references.setdefault(_normalize_lookup_text(alias), reference)
    return references


def _get_default_item_type():
    """Retourne le type article metier par defaut quand le fichier le laisse vide."""

    return (
        ItemType.objects.filter(code__iexact="BIE", is_active=True).first()
        or ItemType.objects.filter(is_active=True).order_by("id").first()
        or ItemType.objects.order_by("id").first()
    )


def _get_default_tax_group():
    """Retourne le groupe fiscal par defaut quand le fichier le laisse vide."""

    return (
        TaxGroup.objects.filter(code__iexact="B", is_active=True).first()
        or TaxGroup.objects.filter(is_active=True).order_by("code").first()
        or TaxGroup.objects.order_by("code").first()
    )


def _build_point_de_vente_cache(accessible_point_de_vente_ids=None):
    """Prepare un cache des points de vente autorises pour l'import."""

    queryset = PointDeVente.objects.all().order_by("id")
    if accessible_point_de_vente_ids is not None:
        queryset = queryset.filter(id__in=accessible_point_de_vente_ids)

    points_de_vente = {}
    for point_de_vente in queryset.iterator(chunk_size=1000):
        normalized_name = _normalize_lookup_text(point_de_vente.nom)
        if normalized_name:
            points_de_vente.setdefault(normalized_name, point_de_vente)
    return points_de_vente


def _normalize_default_points_de_vente(default_point_de_vente=None, default_points_de_vente=None):
    """Normalise les magasins cibles fournis par l'ecran d'import."""

    points = []
    if default_points_de_vente is not None:
        points.extend([point for point in default_points_de_vente if point])
    elif default_point_de_vente:
        points.append(default_point_de_vente)

    unique_points = []
    seen_ids = set()
    for point in points:
        if point.pk in seen_ids:
            continue
        unique_points.append(point)
        seen_ids.add(point.pk)
    return tuple(unique_points)


def _resolve_category(category_name, category_cache, report):
    """Retrouve ou cree la categorie demandee par une ligne valide."""

    category_name = _clean_text(category_name)
    if not category_name:
        return None

    normalized_name = _normalize_lookup_text(category_name)
    category = category_cache.get(normalized_name)
    if category:
        return category

    # Creation automatique choisie pour fluidifier les imports volumineux.
    category = Categorie.objects.create(nom=category_name)
    category_cache[normalized_name] = category
    report.categories_created += 1
    return category


def _product_update_changes(product, row):
    """Retourne les champs qui changeraient pour un produit existant."""

    current_category = _normalize_lookup_text(product.categorie.nom if product.categorie else "")
    incoming_category = _normalize_lookup_text(row.categorie)
    checks = (
        ("nom", _clean_text(product.nom), row.nom),
        ("categorie", current_category, incoming_category),
        ("typeart", getattr(product, "typeart_id", None), getattr(row.typeart, "pk", None)),
        ("taxgroup", getattr(product, "taxgroup_id", None), getattr(row.taxgroup, "pk", None)),
        ("prix_vente", product.prix_vente, row.prix_vente),
        ("unite_mesure", _clean_text(product.unite_mesure or "U").upper(), row.unite_mesure),
        ("actif", bool(product.actif), bool(row.actif)),
        ("est_taxe_specifique", bool(product.est_taxe_specifique), bool(row.est_taxe_specifique)),
        ("taxe_specifique_active", bool(product.taxe_specifique_active), bool(row.taxe_specifique_active)),
        ("taxe_specifique_valeur", _clean_text(product.taxe_specifique_valeur), row.taxe_specifique_valeur),
        (
            "taxe_specifique_description",
            _clean_text(product.taxe_specifique_description),
            row.taxe_specifique_description,
        ),
    )
    changes = [field_name for field_name, current, incoming in checks if current != incoming]

    if row.image_path and getattr(product.image, "name", "") != row.image_path:
        changes.append("image")

    target_points_de_vente = row.points_de_vente or (
        (row.point_de_vente,) if row.point_de_vente else ()
    )
    if row.prix_point_de_vente is not None:
        default_conditionnement = (
            product.conditionnements.filter(par_defaut=True, actif=True).first()
            or product.conditionnements.filter(facteur_conversion=Decimal("1")).first()
        )
        for point_de_vente in target_points_de_vente:
            point_price = ProduitPointVentePrix.objects.filter(
                produit=product,
                conditionnement=default_conditionnement,
                point_de_vente=point_de_vente,
            ).first()
            if (
                point_price is None
                or point_price.prix_vente != row.prix_point_de_vente
                or bool(point_price.actif) != bool(row.actif)
            ):
                changes.append("prix_point_de_vente")
                break

    if row.stock_point_de_vente is not None or row.ensure_stock_point_de_vente:
        for point_de_vente in target_points_de_vente:
            stock = StockPointDeVente.objects.filter(
                produit=product,
                point_de_vente=point_de_vente,
            ).first()
            if stock is None:
                changes.append("stock_point_de_vente")
                break
            if row.stock_point_de_vente is not None and stock.quantite != row.stock_point_de_vente:
                changes.append("stock_point_de_vente")
                break
            if row.prix_point_de_vente is not None and stock.prix_vente != row.prix_point_de_vente:
                changes.append("prix_point_de_vente")
                break

    return tuple(dict.fromkeys(changes))


def _format_update_confirmation_warning(row, changes):
    """Construit le message de confirmation pour une ligne existante."""

    labels = [str(FIELD_LABELS.get(field_name, field_name)) for field_name in changes]
    changed_fields = ", ".join(labels) if labels else str(_("informations produit"))
    return _(
        "Code produit « %(code)s » deja present : champs differents detectes (%(fields)s). "
        "Cochez la confirmation des mises a jour pour appliquer ces changements ; sinon la ligne reste intacte."
    ) % {"code": row.code_sku, "fields": changed_fields}


def _validate_rows(
    worksheet,
    columns,
    report,
    can_create=True,
    can_update=True,
    can_manage_stocks=True,
    can_create_conditionnements=True,
    can_update_conditionnements=True,
    can_edit_prices=True,
    accessible_point_de_vente_ids=None,
    default_point_de_vente=None,
    default_points_de_vente=None,
):
    """Valide tout le fichier avant la moindre ecriture en base."""

    products_by_sku = _build_existing_product_maps()
    points_de_vente_by_name = _build_point_de_vente_cache(accessible_point_de_vente_ids)
    default_points = _normalize_default_points_de_vente(
        default_point_de_vente=default_point_de_vente,
        default_points_de_vente=default_points_de_vente,
    )
    if accessible_point_de_vente_ids is not None:
        default_points = tuple(
            point for point in default_points
            if point.pk in accessible_point_de_vente_ids
        )
    item_types_by_key = _build_item_type_cache()
    tax_groups_by_key = _build_tax_group_cache()
    validated_rows = []
    seen_product_payload_by_sku = {}

    for row_number, row in enumerate(worksheet.iter_rows(min_row=2, values_only=True), start=2):
        if _is_empty_row(row):
            report.ignored += 1
            continue
        if row_number == 2 and _is_template_sample_row(row, columns):
            report.ignored += 1
            continue

        report.total_rows += 1
        row_errors = []
        row_warnings = []

        nom = _clean_text(_get_row_value(row, columns, "nom"))
        code_sku = _normalize_sku(_get_row_value(row, columns, "code_sku"))
        typeart_value = _clean_text(_get_row_value(row, columns, "typeart"))
        taxgroup_value = _clean_text(_get_row_value(row, columns, "taxgroup"))
        categorie = _clean_text(_get_row_value(row, columns, "categorie"))
        unite_mesure = (_clean_text(_get_row_value(row, columns, "unite_mesure")) or "U").upper()
        image_path = _clean_text(_get_row_value(row, columns, "image"))
        point_de_vente_name = _clean_text(_get_row_value(row, columns, "point_de_vente"))
        taxe_specifique_valeur = _clean_text(_get_row_value(row, columns, "taxe_specifique_valeur"))
        taxe_specifique_description = _clean_text(
            _get_row_value(row, columns, "taxe_specifique_description")
        )
        prix_vente_value = _get_row_value(row, columns, "prix_vente")
        prix_vente = _parse_decimal(prix_vente_value)
        prix_point_de_vente = _parse_decimal(_get_row_value(row, columns, "prix_point_de_vente"))
        stock_point_de_vente = _parse_decimal(_get_row_value(row, columns, "stock_point_de_vente"))
        actif = _parse_bool(_get_row_value(row, columns, "actif"), default=True)
        est_taxe_specifique = _parse_bool(
            _get_row_value(row, columns, "est_taxe_specifique"),
            default=False,
        )
        taxe_specifique_active = _parse_bool(
            _get_row_value(row, columns, "taxe_specifique_active"),
            default=False,
        )

        if not nom:
            row_errors.append("Nom obligatoire.")
        if not code_sku:
            row_errors.append("Code produit obligatoire.")
        if prix_vente is None:
            if _clean_text(prix_vente_value):
                row_errors.append("Prix de vente invalide : utilisez un nombre decimal.")
            prix_vente = Decimal("0")
        elif not prix_vente.is_finite():
            row_errors.append("Prix de vente invalide : utilisez un nombre decimal.")
            prix_vente = Decimal("0")
        elif prix_vente < 0:
            row_errors.append("Prix de vente ne peut pas etre negatif.")
        else:
            prix_vente = _round_import_decimal(prix_vente, Produit._meta.get_field("prix_vente").decimal_places)

        normalized_sku = _normalize_sku(code_sku)
        normalized_name = _normalize_product_name(nom)
        existing_product = products_by_sku.get(normalized_sku)
        point_de_vente = None
        points_de_vente = ()
        typeart = None
        taxgroup = None

        if typeart_value:
            typeart = item_types_by_key.get(_normalize_lookup_text(typeart_value))
            if not typeart:
                row_errors.append("Type article DGI introuvable ou inactif.")
        else:
            row_errors.append("Type article DGI obligatoire.")
        if taxgroup_value:
            taxgroup = tax_groups_by_key.get(_normalize_lookup_text(taxgroup_value))
            if not taxgroup:
                row_errors.append("Groupe de taxation introuvable ou inactif.")
        else:
            row_errors.append("Groupe de taxation obligatoire.")
        if image_path and image_path.lower().startswith(("http://", "https://")):
            row_errors.append("Image doit etre un chemin de fichier deja stocke, pas une URL distante.")

        if point_de_vente_name:
            point_de_vente = points_de_vente_by_name.get(_normalize_lookup_text(point_de_vente_name))
            if not point_de_vente:
                row_warnings.append("Point de vente introuvable ou non autorisé : stock/prix PDV ignorés.")
                point_de_vente_name = ""
                prix_point_de_vente = None
                stock_point_de_vente = None
            else:
                points_de_vente = (point_de_vente,)
        elif default_points:
            points_de_vente = default_points
            point_de_vente = points_de_vente[0]
            point_de_vente_name = ", ".join(point.nom for point in points_de_vente)

        if prix_point_de_vente is not None:
            if not prix_point_de_vente.is_finite() or prix_point_de_vente < 0:
                row_warnings.append(_("Prix point de vente invalide (négatif) : valeur ignorée."))
                prix_point_de_vente = None
            else:
                prix_point_de_vente = _round_import_decimal(prix_point_de_vente, ProduitPointVentePrix._meta.get_field("prix_vente").decimal_places)

        if stock_point_de_vente is not None:
            row_warnings.append(_("Stock Excel ignoré : aucune écriture directe de stock n'est autorisée. Utilisez une réception ou un inventaire."))
            stock_point_de_vente = None

        if prix_point_de_vente is not None and not points_de_vente:
            row_warnings.append("Prix point de vente ignoré : point de vente absent.")
            prix_point_de_vente = None

        ensure_stock_point_de_vente = False
        if existing_product:
            from .product_excel_conditionnements import unite_protegee
            if _normalize_lookup_text(existing_product.unite_mesure) != _normalize_lookup_text(unite_mesure) and unite_protegee(existing_product):
                row_errors.append(_("L'unité de base est protégée : ce produit possède du stock ou un historique."))

        product_payload = (
            normalized_name,
            getattr(typeart, "pk", None),
            getattr(taxgroup, "pk", None),
            _normalize_lookup_text(categorie),
            str(prix_vente or ""),
            _normalize_lookup_text(unite_mesure),
            image_path,
            str(actif),
            str(est_taxe_specifique),
            str(taxe_specifique_active),
            taxe_specifique_valeur,
            taxe_specifique_description,
        )
        previous_payload = seen_product_payload_by_sku.get(normalized_sku)
        if previous_payload and previous_payload != product_payload:
            row_errors.append("Code produit repete avec des informations produit differentes.")

        if existing_product and existing_product.prix_vente != prix_vente and (not can_update_conditionnements or not can_edit_prices):
            row_errors.append(_("Permission insuffisante pour modifier les prix du conditionnement."))
        if existing_product and (existing_product.unite_mesure != unite_mesure or existing_product.actif != actif) and not can_update_conditionnements:
            row_errors.append(_("Permission insuffisante pour modifier le conditionnement de base."))
        if prix_point_de_vente is not None and (not can_edit_prices or (existing_product and not can_update_conditionnements)):
            row_errors.append(_("Permission insuffisante pour modifier les prix locaux du conditionnement."))
        if existing_product and not can_update:
            row_errors.append("Permission insuffisante pour mettre a jour ce produit.")
        if not existing_product and not can_create:
            row_errors.append("Permission insuffisante pour creer ce produit.")
        if not existing_product 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 existing_product and points_de_vente and (prix_point_de_vente is not None or stock_point_de_vente is not None):
            # Prix ou stock vise un PDV ou le produit n'est pas vendu (G_Affectation).
            from G_Affectation.services import est_visible, message_non_visible
            row_errors.extend(message_non_visible(existing_product, point) for point in points_de_vente if not est_visible(existing_product, point))

        if row_errors:
            report.errors.append(ProductExcelRowError(row_number=row_number, messages=row_errors, code_produit=code_sku, champ="produit"))
            report.ignored += 1
            report.rejected_rows += 1
            continue
        if row_warnings:
            report.warnings.append(ProductExcelRowWarning(row_number=row_number, messages=row_warnings))

        seen_product_payload_by_sku[normalized_sku] = product_payload
        validated_rows.append(
            _ValidatedProductRow(
                row_number=row_number,
                nom=nom,
                code_sku=code_sku,
                normalized_sku=normalized_sku,
                categorie=categorie,
                typeart=typeart,
                taxgroup=taxgroup,
                prix_vente=prix_vente,
                unite_mesure=unite_mesure,
                image_path=image_path,
                actif=actif,
                est_taxe_specifique=est_taxe_specifique,
                taxe_specifique_active=taxe_specifique_active,
                taxe_specifique_valeur=taxe_specifique_valeur,
                taxe_specifique_description=taxe_specifique_description,
                existing_product=existing_product,
                point_de_vente=point_de_vente,
                points_de_vente=points_de_vente,
                prix_point_de_vente=prix_point_de_vente,
                stock_point_de_vente=stock_point_de_vente,
                ensure_stock_point_de_vente=ensure_stock_point_de_vente,
            )
        )

    return validated_rows


def _import_conditionnements_worksheet(worksheet, report, *, can_create=True, can_update=True, can_edit_prices=True):
    """Valide puis cree les conditionnements d'une feuille dediee."""

    if not can_create:
        report.workbook_errors.append(
            "Permission insuffisante pour importer des conditionnements."
        )
        return

    header_row = next(worksheet.iter_rows(min_row=1, max_row=1, values_only=True), None)
    if not header_row:
        report.workbook_errors.append("La feuille Conditionnements ne contient aucune entete.")
        return

    columns = _conditionnement_columns(header_row)
    required = ("code_sku", "code", "libelle", "facteur_conversion", "prix_vente")
    missing = [field_name for field_name in required if field_name not in columns]
    if missing:
        report.workbook_errors.append(
            "Feuille Conditionnements : colonnes obligatoires manquantes : "
            + ", ".join(missing)
            + "."
        )
        return

    products = {
        _normalize_sku(product.code_sku): product
        for product in Produit.objects.all().iterator(chunk_size=1000)
    }
    existing_codes = {
        _normalize_sku(code)
        for code in ConditionnementProduit.objects.values_list("code", flat=True)
    }
    seen_codes = set()
    seen_default_products = set()
    validated = []

    for row_number, row in enumerate(worksheet.iter_rows(min_row=2, values_only=True), start=2):
        if _is_empty_row(row):
            continue
        if row_number == 2 and tuple(row[: len(CONDITIONNEMENT_SAMPLE_ROW)]) == CONDITIONNEMENT_SAMPLE_ROW:
            continue

        report.total_rows += 1

        errors = []
        code_sku = _normalize_sku(_get_row_value(row, columns, "code_sku"))
        code = _normalize_sku(_get_row_value(row, columns, "code"))
        libelle = _clean_text(_get_row_value(row, columns, "libelle"))
        facteur = _parse_decimal(_get_row_value(row, columns, "facteur_conversion"))
        prix_vente = _parse_decimal(_get_row_value(row, columns, "prix_vente"))
        product = products.get(code_sku)

        bool_values = {}
        bool_defaults = {
            "vendable": True,
            "achetable": True,
            "par_defaut": False,
            "fractionnable": False,
            "actif": True,
        }
        for field_name, default in bool_defaults.items():
            parsed, valid = _parse_bool_strict(
                _get_row_value(row, columns, field_name),
                default=default,
            )
            bool_values[field_name] = parsed
            if not valid:
                errors.append(f"Valeur booleenne invalide pour {field_name}.")

        if not product:
            errors.append("Produit inexistant pour le code produit indique.")
        if not code:
            errors.append("Code conditionnement obligatoire.")
        elif code in existing_codes or code in seen_codes:
            errors.append("Code conditionnement deja utilise.")
        if not libelle:
            errors.append("Libelle obligatoire.")
        if facteur is None or not facteur.is_finite() or facteur <= 0:
            errors.append("Le facteur doit etre strictement superieur a zero.")
        else:
            facteur = _round_import_decimal(facteur, ConditionnementProduit._meta.get_field("facteur_conversion").decimal_places)
            if facteur == 0:
                errors.append(_("Le facteur est trop petit : après arrondi à 3 décimales, il doit être au minimum 0,001."))
        if prix_vente is None or not prix_vente.is_finite() or prix_vente < 0:
            errors.append("Le prix de vente doit etre un nombre positif ou nul.")
        else:
            prix_vente = _round_import_decimal(prix_vente, ConditionnementProduit._meta.get_field("prix_vente").decimal_places)
        if bool_values["par_defaut"] and not bool_values["actif"]:
            errors.append("Un conditionnement par defaut doit etre actif.")
        if product and bool_values["par_defaut"]:
            if product.pk in seen_default_products:
                errors.append("Plusieurs conditionnements par defaut sont declares pour ce produit.")
            if not can_update and product.conditionnements.filter(par_defaut=True).exists():
                errors.append(_("Permission insuffisante pour remplacer le conditionnement par défaut existant."))
        if not can_edit_prices:
            errors.append(_("Permission insuffisante pour définir le prix du conditionnement."))
        candidate = ConditionnementProduit(produit=product, code=code, libelle=libelle,
            facteur_conversion=facteur, prix_vente=prix_vente, **bool_values)
        if not errors:
            try:
                candidate.full_clean()
            except ValidationError as exc:
                errors.extend(exc.messages)

        if errors:
            report.errors.append(
                ProductExcelRowError(
                    row_number=row_number,
                    messages=errors,
                    sheet_name="Conditionnements",
                    code_produit=code_sku,
                    code_conditionnement=code,
                    champ="conditionnement",
                )
            )
            report.conditionnements_ignored += 1
            report.rejected_rows += 1
            continue

        if bool_values["par_defaut"]:
            seen_default_products.add(product.pk)
        seen_codes.add(code)
        validated.append(candidate)

    for conditionnement in validated:
        demoted = conditionnement.produit.conditionnements.filter(par_defaut=True).count() if conditionnement.par_defaut else 0
        conditionnement.save(synchroniser_produit=False)
        report.conditionnements_created += 1
        report.conditionnements_updated += demoted


def import_products_from_excel(
    uploaded_file,
    *,
    can_create=True,
    can_update=True,
    can_manage_stocks=True,
    can_create_conditionnements=True,
    can_update_conditionnements=True,
    can_edit_prices=True,
    accessible_point_de_vente_ids=None,
    default_point_de_vente=None,
    default_points_de_vente=None,
    created_by=None,
    confirm_updates=True,
):
    """Importe les produits depuis un fichier Excel et retourne un rapport detaille."""

    (
        _workbook_class,
        load_workbook,
        _font_class,
        _pattern_fill_class,
        _data_validation_class,
    ) = _load_openpyxl()
    report = ProductExcelImportReport()

    try:
        workbook = load_workbook(uploaded_file, read_only=True, data_only=True)
    except Exception:
        report.workbook_errors.append(str(gettext_lazy("Le fichier Excel est illisible ou corrompu.")))
        return report

    try:
        if "Produits" not in workbook.sheetnames and "Conditionnements" in workbook.sheetnames:
            with transaction.atomic():
                _import_conditionnements_worksheet(
                    workbook["Conditionnements"],
                    report,
                    can_create=can_create_conditionnements,
                    can_update=can_update_conditionnements,
                    can_edit_prices=can_edit_prices,
                )
            return report

        worksheet = workbook["Produits"] if "Produits" in workbook.sheetnames else workbook.active
        header_row = next(worksheet.iter_rows(min_row=1, max_row=1, values_only=True), None)
        if not header_row:
            report.workbook_errors.append(str(gettext_lazy("Le fichier Excel ne contient aucune entete.")))
            return report

        columns = _map_headers(header_row)
        from .product_excel_conditionnements import is_combined_sheet, import_combined_worksheet
        if is_combined_sheet(header_row):
            return import_combined_worksheet(
                worksheet, report, 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, created_by=created_by,
                confirm_updates=confirm_updates,
                default_points_de_vente=_normalize_default_points_de_vente(
                    default_point_de_vente=default_point_de_vente,
                    default_points_de_vente=default_points_de_vente,
                ),
                accessible_point_de_vente_ids=accessible_point_de_vente_ids,
            )
        missing_fields = [
            str(FIELD_LABELS[field_name])
            for field_name in REQUIRED_IMPORT_FIELDS
            if field_name not in columns
        ]
        if missing_fields:
            report.workbook_errors.append(
                str(gettext_lazy("Colonnes obligatoires manquantes : ")) + ", ".join(missing_fields) + "."
            )
            return report

        validated_rows = _validate_rows(
            worksheet,
            columns,
            report,
            can_create=can_create,
            can_update=can_update,
            can_manage_stocks=can_manage_stocks,
            can_create_conditionnements=can_create_conditionnements,
            can_update_conditionnements=can_update_conditionnements,
            can_edit_prices=can_edit_prices,
            accessible_point_de_vente_ids=accessible_point_de_vente_ids,
            default_point_de_vente=default_point_de_vente,
            default_points_de_vente=default_points_de_vente,
        )
        if not validated_rows and report.errors:
            return report

        if not validated_rows and "Conditionnements" in workbook.sheetnames:
            with transaction.atomic():
                _import_conditionnements_worksheet(
                    workbook["Conditionnements"],
                    report,
                    can_create=can_create_conditionnements,
                    can_update=can_update_conditionnements,
                    can_edit_prices=can_edit_prices,
                )
            return report
        if not validated_rows:
            return report

        with transaction.atomic():
            category_cache = _build_category_cache()
            imported_products_by_sku = {
                row.normalized_sku: row.existing_product
                for row in validated_rows
                if row.existing_product is not None
            }
            processed_product_skus = set()
            skipped_update_skus = set()
            for row in validated_rows:
                product = imported_products_by_sku.get(row.normalized_sku)
                if row.normalized_sku in skipped_update_skus:
                    report.ignored += 1
                    continue

                if row.normalized_sku not in processed_product_skus:
                    update_changes = _product_update_changes(product, row) if product else ()
                    if product and update_changes and not confirm_updates:
                        report.pending_updates += 1
                        report.ignored += 1
                        skipped_update_skus.add(row.normalized_sku)
                        report.warnings.append(
                            ProductExcelRowWarning(
                                row_number=row.row_number,
                                messages=[_format_update_confirmation_warning(row, update_changes)],
                            )
                        )
                        processed_product_skus.add(row.normalized_sku)
                        continue

                    category = _resolve_category(row.categorie, category_cache, report)

                    if product:
                        if not update_changes:
                            report.unchanged_products += 1
                        else:
                            report.updated += 1
                        product_update_fields = [
                            field_name
                            for field_name in update_changes
                            if field_name in PRODUCT_MODEL_UPDATE_FIELDS
                        ]
                        update_fields = list(product_update_fields)
                        if product_update_fields:
                            product.nom = row.nom
                            product.code_sku = row.code_sku
                            product.categorie = category
                            product.typeart = row.typeart
                            product.taxgroup = row.taxgroup
                            product.prix_vente = row.prix_vente
                            product.unite_mesure = row.unite_mesure
                            if row.image_path:
                                # L'import Excel reference seulement un fichier deja present dans le stockage.
                                product.image.name = row.image_path
                            product.actif = row.actif
                            product.est_taxe_specifique = row.est_taxe_specifique
                            product.taxe_specifique_active = row.taxe_specifique_active
                            product.taxe_specifique_valeur = row.taxe_specifique_valeur
                            product.taxe_specifique_description = row.taxe_specifique_description
                        if created_by and not product.created_by_id and product_update_fields:
                            product.created_by = created_by
                            update_fields.append("created_by")
                        if update_fields:
                            pack_changes = product.conditionnements.filter(facteur_conversion=1).count() if any(name in product_update_fields for name in ("prix_vente", "unite_mesure", "actif")) else 0
                            product.save(update_fields=update_fields)
                            report.conditionnements_updated += pack_changes
                    else:
                        product = Produit.objects.create(
                            nom=row.nom,
                            code_sku=row.code_sku,
                            categorie=category,
                            typeart=row.typeart,
                            taxgroup=row.taxgroup,
                            prix_vente=row.prix_vente,
                            unite_mesure=row.unite_mesure,
                            image=row.image_path,
                            actif=row.actif,
                            est_taxe_specifique=row.est_taxe_specifique,
                            taxe_specifique_active=row.taxe_specifique_active,
                            taxe_specifique_valeur=row.taxe_specifique_valeur,
                            taxe_specifique_description=row.taxe_specifique_description,
                            created_by=created_by,
                        )
                        report.created += 1
                        report.conditionnements_created += 1

                    imported_products_by_sku[row.normalized_sku] = product
                    processed_product_skus.add(row.normalized_sku)
                    report.imported_product_ids.add(product.pk)

                default_conditionnement = (
                    product.conditionnements.filter(par_defaut=True, actif=True).first()
                    or product.conditionnements.filter(facteur_conversion=Decimal("1")).first()
                )

                # Une selection multiple de magasins applique seulement les prix
                # de la ligne a chaque PDV cible autorise.
                target_points_de_vente = row.points_de_vente or (
                    (row.point_de_vente,) if row.point_de_vente else ()
                )
                for point_de_vente in target_points_de_vente:
                    if row.prix_point_de_vente is not None:
                        point_price, created = ProduitPointVentePrix.objects.update_or_create(
                            conditionnement=default_conditionnement,
                            point_de_vente=point_de_vente,
                            defaults={
                                "produit": product,
                                "prix_vente": row.prix_point_de_vente,
                                "actif": row.actif,
                            },
                        )
                        if created:
                            report.point_prices_created += 1
                        else:
                            report.point_prices_updated += 1


            if "Conditionnements" in workbook.sheetnames:
                _import_conditionnements_worksheet(
                    workbook["Conditionnements"],
                    report,
                    can_create=can_create_conditionnements,
                    can_update=can_update_conditionnements,
                    can_edit_prices=can_edit_prices,
                )
    finally:
        workbook.close()

    return report


def build_products_export_workbook(point_de_vente_queryset=None, *, product_queryset=None, selected_fields=None):
    """Construit le classeur Excel contenant tous les produits."""

    Workbook, _load_workbook, _font_class, _pattern_fill_class, _data_validation_class = _load_openpyxl()
    workbook = Workbook(write_only=True)
    worksheet = workbook.create_sheet(title="Produits")
    export_fields = _normalize_export_fields(selected_fields)
    headers_by_field = {column["field"]: str(column["header"]) for column in PRODUCT_EXCEL_COLUMN_SPECS}
    worksheet.append([headers_by_field[field_name] for field_name in export_fields])

    queryset = product_queryset
    if queryset is None:
        queryset = Produit.objects.select_related("categorie", "typeart", "taxgroup").all()
        queryset = queryset.order_by("nom", "code_sku")
    for produit in queryset.iterator(chunk_size=1000):
        worksheet.append([_get_export_cell_value(produit, field_name) for field_name in export_fields])

    output = BytesIO()
    workbook.save(output)
    return output.getvalue()


def build_products_import_template_workbook():
    """Deux feuilles ; chaque ligne associe un produit à un conditionnement."""

    from .product_excel_conditionnements import build_combined_workbook
    return build_combined_workbook()
