"""Extension du service Excel existant : une ligne Produit + Conditionnement.

Import et modification en masse partagent la validation et les mêmes écritures.
Un groupe produit est atomique : une incohérence rejette toutes ses lignes.
Ce service ne crée ni ne modifie aucun stock, mouvement ou snapshot historique.
"""

from collections import defaultdict
from copy import copy
from decimal import Decimal
from io import BytesIO

from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy, override

from .models import (
    Categorie,
    ConditionnementProduit,
    HistoriquePrixProduit,
    Produit,
    ProduitPointVentePrix,
    StockPointDeVente,
)
from .price_utils import PRICE_SCOPE_GLOBAL, PRICE_SCOPE_PDV, normalize_price_scope
from .product_catalogue_rules import conditionnement_utilise, unite_protegee


# Le format historique à huit colonnes reste reconnu par product_excel.py.
# Les libellés ci-dessous décrivent uniquement le nouveau modèle téléchargé.
COMBINED_COLUMN_SPECS = tuple({"field": field, "header": gettext_lazy(header), "required": required,
    "description": gettext_lazy(fr), "english": en, "example": example, "allowed": allowed}
    for field, header, required, fr, en, example, allowed in (
        ("code_sku", "Code produit *", True, "Identifiant unique du produit, répété pour ses conditionnements.", "Unique product identifier, repeated for its packaging rows.", "JUS001", "Texte unique / Unique text"),
        ("nom", "Nom produit *", True, "Nom commercial, identique pour toutes les lignes du produit.", "Product name, identical across all rows of the same product.", "Jus Orange 33cl", "Texte / Text"),
        ("typeart", "Type article DGI *", True, "Code ou libellé d'un type article DGI actif existant.", "Code or label of an existing active DGI item type.", "BIE", "Références DGI actives / Active DGI references"),
        ("categorie", "Catégorie", False, "Catégorie du produit ; créée automatiquement si absente.", "Product category; automatically created if missing.", "Boissons", "Texte / Text"),
        ("unite_mesure", "Unité de base *", True, "Plus petite unité physique utilisée pour le stock ; modification protégée si le produit possède du stock ou un historique.", "Smallest physical stock unit; changes are blocked when stock or history exists.", "Bouteille", "Texte / Text"),
        ("taxgroup", "Groupe de taxation *", True, "Groupe fiscal DGI du produit, actif et identique sur toutes ses lignes.", "Active DGI tax group assigned to the product, identical across its rows.", "B", "Références DGI actives / Active DGI references"),
        ("actif", "Actif produit", False, "Active ou désactive le produit, indépendamment de ses conditionnements.", "Activates or deactivates the product independently of its packaging.", "Oui", "Oui / Non / Yes / No / True / False / 1 / 0"),
        ("code_conditionnement", "Code conditionnement *", True, "Identifiant unique du conditionnement ; un code historique utilisé est protégé.", "Unique packaging identifier; used historical codes are protected.", "JUS001-C24", "Texte unique / Unique text"),
        ("libelle_conditionnement", "Libellé conditionnement *", True, "Manière d'acheter ou de vendre le produit : pièce, paquet, carton.", "Product packaging or selling unit: piece, pack, carton.", "Carton de 24", "Texte / Text"),
        ("facteur_conversion", "Facteur *", True, "Nombre d'unités de base contenues dans le conditionnement, arrondi automatiquement à 3 décimales ; un facteur utilisé est protégé.", "Number of base units in this packaging, automatically rounded to 3 decimals; a used factor cannot be changed.", "24", "Nombre > 0, arrondi à 3 décimales / Number > 0, rounded to 3 decimals"),
        ("prix_conditionnement", "Prix de vente *", True, "Prix indépendant du conditionnement, dans la devise du catalogue, arrondi automatiquement à 2 décimales ; vide conserve l'existant en modification.", "Independent packaging price in catalogue currency, automatically rounded to 2 decimals; blank keeps the existing price when editing.", "20000", "Nombre >= 0, arrondi à 2 décimales / Number >= 0, rounded to 2 decimals"),
        ("code_barres", "Code-barres", False, "Code-barres facultatif du produit ; vide conserve le code existant lors d'une mise à jour.", "Optional product barcode; blank keeps the existing barcode when updating.", "3012345678901", "Texte unique ou vide / Unique text or blank"),
        ("vendable", "Vendable", False, "Peut être utilisé pour les ventes futures dans le POS.", "Can be used for future POS sales.", "Oui", "Oui / Non / Yes / No / True / False / 1 / 0"),
        ("achetable", "Achetable", False, "Peut être utilisé pour les achats futurs.", "Can be used for future purchases.", "Oui", "Oui / Non / Yes / No / True / False / 1 / 0"),
        ("par_defaut", "Par défaut", False, "Un seul conditionnement actif sélectionné automatiquement par produit.", "Only one active default packaging per product.", "Non", "Oui / Non / Yes / No / True / False / 1 / 0"),
        ("fractionnable", "Fractionnable", False, "Autorise une quantité commerciale décimale ; Non impose une quantité entière.", "Allows decimal commercial quantities; No requires whole quantities.", "Non", "Oui / Non / Yes / No / True / False / 1 / 0"),
        ("actif_conditionnement", "Actif conditionnement", False, "Active ou désactive le conditionnement pour les opérations futures.", "Activates or deactivates packaging for future operations.", "Oui", "Oui / Non / Yes / No / True / False / 1 / 0"),
    ))
COMBINED_HEADERS = tuple(column["header"] for column in COMBINED_COLUMN_SPECS)
COMBINED_FIELDS = tuple(column["field"] for column in COMBINED_COLUMN_SPECS)
# Ligne d'aide visible du modèle d'import validé par le client. Elle n'est
# ignorée que si les 17 valeurs de la ligne 2 sont intactes.
COMBINED_TEMPLATE_SAMPLE_ROW = (
    "GBM-001", "APPLICATION FACCONTROL", "BIE", "Catégorie Exemple", "PCS", "B", "Oui",
    "GBM-001-PCS", "Unité", 1, 10, "007765565656", "Oui", "Oui", "Oui", "Non", "Oui",
)
BOOL_DEFAULTS = {"actif": True, "vendable": True, "achetable": True, "par_defaut": False, "fractionnable": False, "actif_conditionnement": True}
PACK_FIELDS = {"code_conditionnement": "code", "libelle_conditionnement": "libelle", "facteur_conversion": "facteur_conversion", "prix_conditionnement": "prix_vente", "vendable": "vendable", "achetable": "achetable", "par_defaut": "par_defaut", "fractionnable": "fractionnable", "actif_conditionnement": "actif"}
PRODUCT_FIELDS = ("nom", "typeart", "categorie", "unite_mesure", "taxgroup", "actif", "code_barres")
MAX_DATA_ROWS = 50000


def combined_columns(headers):
    from .product_excel import HEADER_ALIASES, _normalize_header_text
    aliases = {**HEADER_ALIASES, **{_normalize_header_text(column["header"]): column["field"] for column in COMBINED_COLUMN_SPECS},
        "product code": "code_sku", "product name": "nom", "dgi item type": "typeart", "base unit": "unite_mesure", "product active": "actif", "active product": "actif",
        "packaging code": "code_conditionnement", "code conditionnement": "code_conditionnement", "packaging label": "libelle_conditionnement", "libelle conditionnement": "libelle_conditionnement",
        "label": "libelle_conditionnement", "factor": "facteur_conversion", "facteur de conversion": "facteur_conversion", "sale price": "prix_conditionnement", "selling price": "prix_conditionnement", "prix vente": "prix_conditionnement",
        "sellable": "vendable", "purchasable": "achetable", "default": "par_defaut", "fractional": "fractionnable", "fractionable": "fractionnable", "packaging active": "actif_conditionnement", "active packaging": "actif_conditionnement",
        "fractional quantities allowed": "fractionnable",
        "id produit": "id_produit", "product id": "id_produit", "id conditionnement": "id_conditionnement", "packaging id": "id_conditionnement"}
    columns = {}
    for index, header in enumerate(headers):
        field = aliases.get(_normalize_header_text(header))
        if field:
            if field in columns:
                raise ValidationError(_("Colonne répétée : %(field)s.") % {"field": field})
            columns[field] = index
    return columns


def is_combined_sheet(headers):
    from .product_excel import _normalize_header_text
    return any(_normalize_header_text(header) in ("code conditionnement", "packaging code", "id conditionnement", "packaging id", "libelle conditionnement", "packaging label", "actif conditionnement", "packaging active", "active packaging") for header in headers)


def _is_combined_template_sample_row(raw, columns):
    from .product_excel import _get_row_value
    return all(
        field in columns
        and _get_row_value(raw, columns, field) == example
        for field, example in zip(COMBINED_FIELDS, COMBINED_TEMPLATE_SAMPLE_ROW)
    )


def _add_error(report, record, field, message):
    from .product_excel import ProductExcelRowError
    label = next((str(column["header"]) for column in COMBINED_COLUMN_SPECS if column["field"] == field), str(field))
    report.errors.append(ProductExcelRowError(
        record["row"], [f"{label} : {message}"],
        code_produit=record["sku"],
        code_conditionnement=record.get("pack_code", ""), champ=str(field),
        field_label=label,
    ))
    if not hasattr(report, "_error_rows"):
        report._error_rows = set()
    report._error_rows.add(record["row"])


def _reject_group(report, records):
    from .product_excel import ProductExcelRowError
    bad_rows = getattr(report, "_error_rows", set())
    error_lines = ", ".join(str(record["row"]) for record in records if record["row"] in bad_rows)
    for record in records:
        if record["row"] not in bad_rows:
            report.errors.append(ProductExcelRowError(
                record["row"],
                [_("Produit %(sku)s non importé : corrigez les erreurs aux lignes %(rows)s, puis relancez le fichier. Tous ses conditionnements sont rejetés ensemble.") % {"sku": record["sku"], "rows": error_lines}],
                code_produit=record["sku"], code_conditionnement=record.get("pack_code", ""), champ=str(_("Produit")),
            ))
    report.rejected_rows += len(records)
    report.ignored += len(records)
    report.conditionnements_ignored += len(records)


def _numeric_error_message(raw, value, field):
    """Explique les valeurs invalides ; les décimales valides sont arrondies."""
    from .product_excel import _clean_text

    entered = _clean_text(raw)
    factor = field == "facteur_conversion"
    rule = (_("un nombre strictement supérieur à 0") if factor
            else _("un nombre supérieur ou égal à 0"))
    if not entered:
        return _("Valeur manquante. Saisissez %(rule)s.") % {"rule": rule}
    if value is None or not value.is_finite():
        return _("Valeur « %(value)s » invalide. Saisissez %(rule)s.") % {"value": entered, "rule": rule}
    if factor and value <= 0:
        return _("Facteur « %(value)s » refusé : il doit être strictement supérieur à 0 et indiquer le nombre d'unités de base contenues dans le conditionnement.") % {"value": entered}
    if not factor and value < 0:
        return _("Prix « %(value)s » refusé : le prix de vente doit être supérieur ou égal à 0.") % {"value": entered}
    return _("Valeur « %(value)s » invalide. Saisissez %(rule)s.") % {"value": entered, "rule": rule}


def _match_packs_by_factor(records, columns, existing, packs_by_code):
    """Même code produit : relie chaque nouveau code conditionnement au conditionnement existant de même facteur.

    Un produit créé depuis le formulaire porte un code automatique (CP-…) : le
    fichier doit le mettre à jour, pas créer un second conditionnement identique.
    """
    from .product_excel import _clean_text, _get_row_value, _normalize_lookup_text, _parse_decimal, _round_import_decimal

    places = ConditionnementProduit._meta.get_field("facteur_conversion").decimal_places
    claimed, pending, matches = set(), [], {}
    for record in records:
        raw_id = _clean_text(_get_row_value(record["raw"], columns, "id_conditionnement"))
        known = packs_by_code.get(record["pack_code"])
        if known:
            claimed.add(known.pk)
        if raw_id.isdigit():
            claimed.add(int(raw_id))
        if not (known or raw_id or not record["pack_code"]):
            pending.append(record)
    for record in pending:
        factor = _parse_decimal(_get_row_value(record["raw"], columns, "facteur_conversion"))
        if factor is None or not factor.is_finite() or factor <= 0:
            continue
        factor = _round_import_decimal(factor, places)
        label = _normalize_lookup_text(_get_row_value(record["raw"], columns, "libelle_conditionnement"))
        candidates = [pack for pack in existing if pack.pk not in claimed and pack.facteur_conversion == factor]
        if candidates:
            pack = min(candidates, key=lambda pack: (_normalize_lookup_text(pack.libelle) != label, not pack.par_defaut, not pack.actif, pack.pk))
            claimed.add(pack.pk)
            matches[record["row"]] = pack
    return matches


def import_combined_worksheet(
    worksheet, report, *, can_create=True, can_update=True,
    can_create_conditionnements=True, can_update_conditionnements=True,
    can_edit_prices=True, created_by=None, confirm_updates=False,
    modification=False, pdv=None, portee_prix=PRICE_SCOPE_GLOBAL,
    commentaire_prix="", default_points_de_vente=None,
    accessible_point_de_vente_ids=None,
):
    from .product_excel import (
        ProductExcelRowWarning,
        _build_category_cache,
        _build_item_type_cache,
        _build_tax_group_cache,
        _clean_text,
        _get_row_value,
        _is_empty_row,
        _normalize_header_text,
        _normalize_lookup_text,
        _normalize_sku,
        _parse_bool_strict,
        _parse_decimal,
        _round_import_decimal,
    )
    from G_Scan.services import code_used_by_other_product, normalize_code
    headers = next(worksheet.iter_rows(min_row=1, max_row=1, values_only=True), ())
    try:
        columns = combined_columns(headers)
    except ValidationError as exc:
        report.workbook_errors.extend(exc.messages)
        return report
    required = ("code_sku", "code_conditionnement") if modification else tuple(col["field"] for col in COMBINED_COLUMN_SPECS if col["required"])
    missing = [str(next(col["header"] for col in COMBINED_COLUMN_SPECS if col["field"] == field)) for field in required if field not in columns]
    if missing:
        report.workbook_errors.append(_("Colonnes obligatoires manquantes : %(fields)s.") % {"fields": ", ".join(missing)})
        return report
    stock_headers = {"quantite stock", "seuil", "seuil alerte", "seuil d alerte", "qty", "alert"}
    if any(field in columns for field in ("stock_point_de_vente", "quantite", "seuil_alerte")) or any(_normalize_header_text(header) in stock_headers for header in headers):
        report.workbook_errors.append(str(_("Les colonnes de stock sont interdites. Utilisez les réceptions d'achats ou les inventaires.")))
        return report
    groups, code_rows = defaultdict(list), defaultdict(list)
    for number, raw in enumerate(worksheet.iter_rows(min_row=2, values_only=True), 2):
        if _is_empty_row(raw):
            continue
        if not modification and number == 2 and _is_combined_template_sample_row(raw, columns):
            report.ignored += 1
            continue
        if report.total_rows >= MAX_DATA_ROWS:
            report.workbook_errors.append(str(_("Le fichier dépasse 50 000 lignes. Fractionnez l'import.")))
            return report
        record = {
            "row": number,
            "sku": _normalize_sku(_get_row_value(raw, columns, "code_sku")),
            "pack_code": _normalize_sku(_get_row_value(raw, columns, "code_conditionnement")),
            "barcode": normalize_code(_get_row_value(raw, columns, "code_barres")),
            "raw": raw,
        }
        report.total_rows += 1
        groups[record["sku"]].append(record)
        code_rows[record["pack_code"]].append(record)
    products = {_normalize_sku(product.code_sku): product for product in Produit.objects.filter(code_sku__in=list(groups)).select_related("categorie", "typeart", "taxgroup")}
    product_ids = [product.pk for product in products.values()]
    packs = list(ConditionnementProduit.objects.filter(Q(produit_id__in=product_ids) | Q(code__in=list(code_rows))))
    packs_by_code = {_normalize_sku(pack.code): pack for pack in packs}
    packs_by_id = {pack.pk: pack for pack in packs}
    packs_by_product = defaultdict(list)
    for pack in packs:
        packs_by_product[pack.produit_id].append(pack)
    from .product_excel_batch import IMPORT_BATCH_SIZE, apply_import_batch, prepare_group_packs, protected_catalogue_ids
    protected_products, used_packs = protected_catalogue_ids(product_ids, list(packs_by_id))
    item_types, tax_groups = _build_item_type_cache(), _build_tax_group_cache()
    category_cache = _build_category_cache()
    portee_prix = normalize_price_scope(portee_prix)
    target_points = (pdv,) if modification and pdv else tuple(default_points_de_vente or ())
    if accessible_point_de_vente_ids is not None:
        target_points = tuple(point for point in target_points if point.pk in accessible_point_de_vente_ids)
    local_prices = {
        (price.conditionnement_id, price.point_de_vente_id): price
        for price in ProduitPointVentePrix.objects.filter(
            conditionnement_id__in=packs_by_id, point_de_vente__in=target_points
        )
    }
    if portee_prix == PRICE_SCOPE_PDV and pdv is None:
        report.workbook_errors.append(str(_("Un point de vente est obligatoire pour modifier le prix localement.")))
        return report
    for code, records in code_rows.items():
        if code and len(records) > 1:
            for record in records:
                _add_error(report, record, "code_conditionnement", _("Code conditionnement dupliqué aux lignes %(rows)s (une ligne identique est également interdite).") % {"rows": ", ".join(str(row["row"]) for row in records)})
    barcode_rows = defaultdict(list)
    for records in groups.values():
        for record in records:
            if record["barcode"]:
                barcode_rows[record["barcode"].casefold()].append(record)
    for records in barcode_rows.values():
        product_codes = {record["sku"] for record in records}
        if len(product_codes) > 1:
            for record in records:
                _add_error(
                    report,
                    record,
                    "code_barres",
                    _("Ce code-barres est attribué à plusieurs produits dans le fichier : %(products)s.")
                    % {"products": ", ".join(sorted(product_codes))},
                )
    plans = []
    barcode_conflict_cache = {}
    # Un prix pour un PDV ou le produit n'est pas vendu (G_Affectation) est une
    # erreur de ligne : l'import ne rend jamais un produit visible en silence.
    from G_Affectation.services import message_non_visible, points_par_produit
    restricted_points = points_par_produit(product_ids) if target_points else {}
    for sku, records in groups.items():
        product = products.get(sku)
        if product and product.pk in restricted_points:
            for point in target_points:
                if point.pk not in restricted_points[product.pk]:
                    for record in records:
                        _add_error(report, record, "code_sku", _("%(message)s Rendez-le vendable dans ce point de vente depuis Affectation Produit, ou retirez ce point de vente de l'import.") % {
                            "message": message_non_visible(product, point),
                        })
        baseline = None
        declared_defaults = []
        matched_by_factor = _match_packs_by_factor(records, columns, packs_by_product[product.pk], packs_by_code) if product else {}
        for record in records:
            raw = record["raw"]
            get = lambda field: _get_row_value(raw, columns, field)
            values = {}
            pack = packs_by_code.get(record["pack_code"])
            raw_pack_id = _clean_text(get("id_conditionnement"))
            raw_product_id = _clean_text(get("id_produit"))
            if raw_product_id and (not product or raw_product_id != str(product.pk)):
                _add_error(report, record, "id_produit", _("L'ID Produit est en lecture seule et doit correspondre au code produit."))
            if raw_pack_id:
                try:
                    identified = packs_by_id.get(int(raw_pack_id))
                except ValueError:
                    identified = None
                if not identified or (product and identified.produit_id != product.pk):
                    _add_error(report, record, "id_conditionnement", _("ID conditionnement inexistant ou appartenant à un autre produit."))
                elif pack and pack.pk != identified.pk:
                    _add_error(report, record, "code_conditionnement", _("Le code et l'ID identifient deux conditionnements différents."))
                else:
                    pack = identified
            if pack is None and record["row"] in matched_by_factor:
                pack = matched_by_factor[record["row"]]
            if pack and (not product or pack.produit_id != product.pk):
                _add_error(report, record, "code_conditionnement", _("Ce code conditionnement appartient déjà à un autre produit."))
            if not sku:
                _add_error(report, record, "code_sku", _("Code produit obligatoire."))
            if not record["pack_code"]:
                _add_error(report, record, "code_conditionnement", _("Code conditionnement obligatoire."))
            for field in PRODUCT_FIELDS:
                cell = get(field)
                if modification and product and _clean_text(cell) == "":
                    current = getattr(product, field)
                    values[field] = current.nom if field == "categorie" and current else ("" if field == "categorie" else current)
                elif field in ("typeart", "taxgroup"):
                    cache = item_types if field == "typeart" else tax_groups
                    values[field] = cache.get(_normalize_lookup_text(cell))
                    if not values[field]:
                        _add_error(report, record, field, _("Référence DGI obligatoire, introuvable ou inactive : %(value)s.") % {"value": _clean_text(cell) or "—"})
                elif field == "actif":
                    values[field], valid = _parse_bool_strict(cell, default=True)
                    if not valid:
                        _add_error(report, record, field, _("Valeur Oui/Non invalide."))
                elif field == "code_barres":
                    entered_barcode = normalize_code(cell)
                    values[field] = (
                        product.code_barres
                        if product and not entered_barcode
                        else (entered_barcode or None)
                    )
                    if values[field]:
                        conflict_key = (values[field].casefold(), product.pk if product else None)
                        if conflict_key not in barcode_conflict_cache:
                            barcode_conflict_cache[conflict_key] = code_used_by_other_product(
                                values[field],
                                product_id=product.pk if product else None,
                            )
                        if barcode_conflict_cache[conflict_key]:
                            _add_error(
                                report,
                                record,
                                field,
                                _("Ce code est déjà utilisé par un autre produit ou conditionnement : le scan serait ambigu."),
                            )
                else:
                    values[field] = _clean_text(cell)
                    if field in ("nom", "unite_mesure") and not values[field]:
                        _add_error(report, record, field, _("Champ obligatoire."))
            signature = tuple(getattr(values[field], "pk", _normalize_lookup_text(values[field])) for field in PRODUCT_FIELDS)
            if baseline is not None and signature != baseline:
                for field, before, after in zip(PRODUCT_FIELDS, baseline, signature):
                    if before != after:
                        _add_error(report, record, field, _("Informations générales incohérentes pour le même code produit (ligne %(row)s).") % {"row": records[0]["row"]})
            baseline = signature if baseline is None else baseline
            pack_values = {}
            for field, attribute in PACK_FIELDS.items():
                cell = get(field)
                if field == "code_conditionnement":
                    value = record["pack_code"]
                elif modification and pack and _clean_text(cell) == "":
                    value = getattr(pack, attribute)
                elif field in BOOL_DEFAULTS:
                    value, valid = _parse_bool_strict(cell, default=BOOL_DEFAULTS[field])
                    if not valid:
                        _add_error(report, record, field, _("Valeur Oui/Non invalide."))
                elif field in ("facteur_conversion", "prix_conditionnement"):
                    value = _parse_decimal(cell)
                    positive = field == "facteur_conversion"
                    if value is None or not value.is_finite() or value < 0 or (positive and value <= 0):
                        _add_error(report, record, field, _numeric_error_message(cell, value, field))
                        value = None
                    else:
                        places = ConditionnementProduit._meta.get_field(attribute).decimal_places
                        value = _round_import_decimal(value, places)
                        if positive and value == 0:
                            _add_error(report, record, field, _("Le facteur est trop petit : après arrondi à 3 décimales, il doit être au minimum 0,001."))
                else:
                    value = _clean_text(cell)
                    if not value:
                        _add_error(report, record, field, _("Champ obligatoire."))
                pack_values[attribute] = value
            if record["row"] in matched_by_factor:
                if pack.pk in used_packs:
                    # Un code déjà présent dans les ventes ou le stock reste celui de l'historique.
                    pack_values["code"] = pack.code
                    note = _("Conditionnement existant %(old)s (même facteur) mis à jour ; son code est conservé car il figure déjà dans l'historique.")
                else:
                    note = _("Conditionnement existant %(old)s (même facteur) mis à jour et renommé %(new)s.")
                record["note"] = str(note % {"old": pack.code, "new": record["pack_code"]})
            if pack_values["par_defaut"]:
                if pack_values["actif"]:
                    declared_defaults.append(record)
                elif not (pack and pack.par_defaut and not pack.actif):
                    _add_error(report, record, "par_defaut", _("Un conditionnement par défaut doit être actif."))
            if record["row"] not in getattr(report, "_error_rows", set()):
                trial_pack = copy(pack) if pack else ConditionnementProduit()
                for field, value in pack_values.items():
                    setattr(trial_pack, field, value)
                try:
                    trial_pack.clean_fields(exclude=["produit", "created_at", "updated_at"])
                except ValidationError as exc:
                    reverse_fields = {attribute: field for field, attribute in PACK_FIELDS.items()}
                    for field, messages in exc.message_dict.items():
                        for message in messages:
                            _add_error(report, record, reverse_fields.get(field, field), message)
            if product and _normalize_lookup_text(product.unite_mesure) != _normalize_lookup_text(values["unite_mesure"]) and product.pk in protected_products:
                _add_error(report, record, "unite_mesure", _("L'unité de base est protégée : ce produit possède du stock ou un historique."))
            if pack and (pack.facteur_conversion != pack_values["facteur_conversion"] or pack.code != pack_values["code"]) and pack.pk in used_packs:
                _add_error(report, record, "facteur_conversion" if pack.facteur_conversion != pack_values["facteur_conversion"] else "code_conditionnement", _("Facteur ou code historique utilisé protégé. Désactivez ce conditionnement et créez-en un nouveau."))
            if not pack and product:
                # Sans ID, un renommage d'un code historique n'est pas une
                # création silencieuse d'un doublon portant le même libellé.
                for historical in packs_by_product[product.pk]:
                    if _normalize_lookup_text(historical.libelle) == _normalize_lookup_text(pack_values["libelle"]) and historical.pk in used_packs:
                        _add_error(report, record, "code_conditionnement", _("Ce libellé correspond à un conditionnement historique utilisé. Conservez son code ou choisissez un nouveau libellé."))
                        break
            if not product and not can_create:
                _add_error(report, record, "code_sku", _("Permission insuffisante pour créer un produit."))
            product_changed = product and any((getattr(product, field).nom if field == "categorie" and getattr(product, field) else ("" if field == "categorie" else getattr(product, field))) != values[field] for field in PRODUCT_FIELDS)
            if product_changed and not can_update:
                _add_error(report, record, "produit", _("Permission insuffisante pour modifier un produit."))
            if not pack and not can_create_conditionnements:
                _add_error(report, record, "conditionnement", _("Permission insuffisante pour créer un conditionnement."))
            price_changed = pack is None or pack.prix_vente != pack_values["prix_vente"]
            if portee_prix == PRICE_SCOPE_PDV and pack:
                local = local_prices.get((pack.pk, pdv.pk))
                price_changed = (local.prix_vente if local and local.actif else pack.prix_vente) != pack_values["prix_vente"]
            target_price_changed = bool(pack and any(
                (price := local_prices.get((pack.pk, point.pk))) is None
                or price.prix_vente != pack_values["prix_vente"] or not price.actif
                for point in target_points
            ))
            price_changed = price_changed or target_price_changed
            if price_changed and not can_edit_prices:
                _add_error(report, record, "prix_conditionnement", _("Permission insuffisante pour modifier les prix."))
            pack_changed = pack and any(
                getattr(pack, field) != value for field, value in pack_values.items()
                if not (modification and portee_prix == PRICE_SCOPE_PDV and field == "prix_vente")
            )
            if pack and (pack_changed or price_changed) and not can_update_conditionnements:
                _add_error(report, record, "conditionnement", _("Permission insuffisante pour modifier un conditionnement."))
            record.update(product_values=values, pack_values=pack_values, pack=pack, changed=bool(product_changed or pack is None or pack_changed or (pack and price_changed)), product_changed=bool(product_changed), default_specified=bool(_clean_text(get("par_defaut"))), target_price_changed=target_price_changed)
        if len(declared_defaults) > 1:
            conflicting = ", ".join(
                _("%(code)s (ligne %(row)s)") % {"code": record["pack_code"], "row": record["row"]}
                for record in declared_defaults
            )
            for record in declared_defaults:
                _add_error(report, record, "par_defaut", _("Plusieurs conditionnements sont marqués « Par défaut = Oui » pour le produit %(sku)s : %(packs)s. Conservez « Oui » sur un seul conditionnement actif et mettez « Non » sur les autres.") % {"sku": sku, "packs": conflicting})
        elif product and declared_defaults:
            chosen = declared_defaults[0]
            chosen_id = chosen["pack"].pk if chosen["pack"] else None
            if any(pack.par_defaut and pack.actif and pack.pk != chosen_id for pack in packs_by_product[product.pk]):
                chosen["changed"] = True
                if not can_update_conditionnements:
                    _add_error(report, chosen, "par_defaut", _("Permission insuffisante pour remplacer le conditionnement par défaut existant."))
        if any(record["row"] in getattr(report, "_error_rows", set()) for record in records):
            _reject_group(report, records)
            continue
        trial_product = copy(product) if product else Produit(code_sku=sku, prix_vente=ZERO_PRICE, created_by=created_by)
        for field, value in records[0]["product_values"].items():
            if field != "categorie":
                setattr(trial_product, field, value)
        try:
            trial_product.clean_fields(exclude=["categorie", "typeart", "taxgroup", "created_by", "created_at", "update_at"])
            if records[0]["product_values"]["categorie"]:
                Categorie._meta.get_field("nom").clean(records[0]["product_values"]["categorie"], None)
            final, prepared, pack_changes = prepare_group_packs(trial_product, records, packs_by_product.get(product.pk, []) if product else [], modification=modification, portee_prix=portee_prix)
            if pack_changes:
                records[0]["changed"] = True
                if not can_update_conditionnements:
                    raise ValidationError({"conditionnement": _("Permission insuffisante pour modifier un conditionnement.")})
        except ValidationError as exc:
            for field, messages in (exc.message_dict if hasattr(exc, "message_dict") else {"categorie": exc.messages}).items():
                for message in messages:
                    _add_error(report, records[0], field, message)
            _reject_group(report, records)
            continue
        if product and any(record["changed"] for record in records) and not confirm_updates:
            report.pending_updates += 1
            report.ignored += len(records)
            report.warnings.append(ProductExcelRowWarning(records[0]["row"], [str(_("Confirmez les mises à jour : ce produit ou ses conditionnements existants ont changé. Tout le groupe reste intact."))], code_produit=sku))
            continue
        if product and not any(record["changed"] for record in records):
            report.imported_product_ids.add(product.pk)
            report.unchanged_products += 1
            continue
        for record in records:
            if record.get("note"):
                report.warnings.append(ProductExcelRowWarning(record["row"], [record["note"]], code_produit=sku, code_conditionnement=record["pack_code"]))
        plans.append((product, records))
    for start in range(0, len(plans), IMPORT_BATCH_SIZE):
        batch = plans[start:start + IMPORT_BATCH_SIZE]
        try:
            stats, imported_ids = apply_import_batch(batch, category_cache, created_by=created_by, modification=modification, pdv=pdv,
                portee_prix=portee_prix, target_points=target_points, commentaire_prix=commentaire_prix)
        except (ValidationError, IntegrityError):
            # Un conflit concurrent ne doit pas empêcher les autres produits.
            for product, records in batch:
                try:
                    with transaction.atomic():
                        stats = _apply_group(product, records, category_cache.copy(), created_by=created_by, modification=modification, pdv=pdv,
                            portee_prix=portee_prix, commentaire_prix=commentaire_prix, default_points_de_vente=default_points_de_vente,
                            accessible_point_de_vente_ids=accessible_point_de_vente_ids)
                except (ValidationError, IntegrityError) as exc:
                    messages = exc.message_dict if isinstance(exc, ValidationError) and hasattr(exc, "message_dict") else {"produit": getattr(exc, "messages", [str(_("Conflit d'intégrité : le produit ou un code conditionnement a changé. Rechargez le fichier."))])}
                    for field, errors in messages.items():
                        for message in errors:
                            _add_error(report, getattr(exc, "excel_record", records[0]), field, message)
                    _reject_group(report, records)
                    continue
                report.imported_product_ids.add(stats.pop("product_id"))
                if product:
                    stats["updated"] = int(any(stats[field] for field in ("updated", "conditionnements_created", "conditionnements_updated", "point_prices_created", "point_prices_updated")))
                    stats["unchanged_products"] = int(not stats["updated"])
                category = stats.pop("category_obj")
                if category:
                    category_cache[_normalize_lookup_text(category.nom)] = category
                for field, count in stats.items():
                    setattr(report, field, getattr(report, field) + count)
        else:
            report.imported_product_ids.update(imported_ids)
            for field, count in stats.items():
                setattr(report, field, getattr(report, field) + count)
    return report


def _apply_group(
    product, records, category_cache, *, created_by, modification, pdv,
    portee_prix, commentaire_prix, default_points_de_vente,
    accessible_point_de_vente_ids,
):
    from .product_excel import _normalize_lookup_text
    from .models import Categorie
    stats = dict(created=0, updated=0, categories_created=0, conditionnements_created=0, conditionnements_updated=0, point_prices_created=0, point_prices_updated=0)
    product_values = records[0]["product_values"].copy()
    category_name = product_values.pop("categorie")
    category = category_cache.get(_normalize_lookup_text(category_name)) if category_name else None
    if category_name and category is None:
        category = Categorie.objects.create(nom=category_name)
        stats["categories_created"] += 1
    product_values["categorie"] = category
    created = product is None
    if created:
        product = Produit(code_sku=records[0]["sku"], created_by=created_by, prix_vente=ZERO_PRICE, **product_values)
        product.full_clean()
        product.save()
        stats["created"] = 1
    else:
        product = Produit.objects.select_for_update().get(pk=product.pk)
        if _normalize_lookup_text(product.unite_mesure) != _normalize_lookup_text(product_values["unite_mesure"]) and unite_protegee(product):
            raise ValidationError({"unite_mesure": _("L'unité de base est protégée : ce produit possède du stock ou un historique.")})
        changes = [field for field, value in product_values.items() if getattr(product, field) != value]
        for field, value in product_values.items():
            setattr(product, field, value)
        product.full_clean()
        if changes:
            product.save(update_fields=changes, synchroniser_conditionnement=False)
            stats["updated"] = 1
    # Réutiliser le conditionnement automatique pour éviter une quatrième
    # ligne CP-* fantôme à la création d'un produit avec trois conditionnements.
    auto_pack = product.conditionnements.select_for_update().get() if created else None
    ordered = sorted(records, key=lambda record: (record["pack_values"]["facteur_conversion"] != Decimal("1"), record["row"]))
    explicit_default = next((record for record in ordered if record["pack_values"]["par_defaut"] and record["pack_values"]["actif"]), None)
    existing = list(product.conditionnements.select_for_update().order_by("pk"))
    original_defaults = {pack.pk for pack in existing if pack.par_defaut}
    final = {pack.pk: pack for pack in existing}
    prepared = []
    for record in ordered:
        source = record["pack"]
        pack = ConditionnementProduit.objects.select_for_update().get(pk=source.pk) if source else (auto_pack if auto_pack is not None else ConditionnementProduit(produit=product))
        auto_pack = None
        values = record["pack_values"].copy()
        if source and (pack.facteur_conversion != values["facteur_conversion"] or pack.code != values["code"]) and conditionnement_utilise(pack):
            raise ValidationError({"facteur_conversion": _("Facteur ou code historique utilisé protégé. Désactivez ce conditionnement et créez-en un nouveau.")})
        if source and modification and portee_prix == PRICE_SCOPE_PDV:
            values["prix_vente"] = pack.prix_vente
        old_price = pack.prix_pour_point_de_vente(pdv) if source and portee_prix == PRICE_SCOPE_PDV else (pack.prix_vente if source else None)
        changed_fields = [field for field, value in values.items() if getattr(pack, field) != value]
        for field, value in values.items():
            setattr(pack, field, value)
        pack.produit = product
        final[pack.pk if pack.pk else -record["row"]] = pack
        prepared.append((record, pack, changed_fields, old_price))
    if explicit_default:
        chosen = next(pack for record, pack, *pack_details in prepared if record is explicit_default)
        for pack in final.values():
            if pack is not chosen and pack.actif:
                pack.par_defaut = False
    defaults = [pack for pack in final.values() if pack.par_defaut and pack.actif]
    active = [pack for pack in final.values() if pack.actif]
    if not defaults and active and (not modification or (created and not any(record["default_specified"] for record in records))):
        preferred = [] if created else [pack for pack in active if pack.pk in original_defaults]
        chosen = min(preferred or active, key=lambda pack: (pack.facteur_conversion, pack.code))
        chosen.par_defaut = True
        defaults = [chosen]
    if len(defaults) > 1 or (product.actif and not defaults):
        raise ValidationError({"par_defaut": _("Un produit actif doit avoir un seul conditionnement actif par défaut.")})
    prepared_ids = {record["pack"].pk for record, pack, changes, old_price in prepared if record["pack"]}
    for pack in final.values():
        if pack.pk in original_defaults and not pack.par_defaut and pack.pk not in prepared_ids and not created:
            pack.save(update_fields=["par_defaut"], synchroniser_produit=False)
            stats["conditionnements_updated"] += 1
    for record, pack, changed_fields, old_price in prepared:
        # Model.clean() protège le facteur utilisé et valide limites/précision.
        if record["pack"]:
            changed_fields = [field for field in PACK_FIELDS.values() if getattr(record["pack"], field) != getattr(pack, field)]
        if not record["pack"] or changed_fields:
            try:
                pack.save(synchroniser_produit=False)
            except ValidationError as exc:
                exc.excel_record = record
                raise
        if record["pack"]:
            if changed_fields:
                stats["conditionnements_updated"] += 1
        else:
            stats["conditionnements_created"] += 1
        new_price = record["pack_values"]["prix_vente"]
        target_points = (pdv,) if modification and pdv else tuple(default_points_de_vente or ())
        if accessible_point_de_vente_ids is not None:
            target_points = tuple(point for point in target_points if point.pk in accessible_point_de_vente_ids)
        if modification and portee_prix == PRICE_SCOPE_GLOBAL and old_price != new_price:
            ProduitPointVentePrix.objects.filter(conditionnement=pack).update(prix_vente=new_price)
        for point in target_points:
            current = ProduitPointVentePrix.objects.filter(conditionnement=pack, point_de_vente=point).first()
            if current and current.prix_vente == new_price and current.actif and current.produit_id == product.pk:
                continue
            local_price, new = ProduitPointVentePrix.objects.update_or_create(conditionnement=pack, point_de_vente=point, defaults={"produit": product, "prix_vente": new_price, "actif": True})
            stats["point_prices_created" if new else "point_prices_updated"] += 1
        if modification and old_price is not None and old_price != new_price:
            HistoriquePrixProduit.objects.create(produit=product, ancien_prix=old_price, nouveau_prix=new_price, portee=portee_prix, point_de_vente=pdv if portee_prix == PRICE_SCOPE_PDV else None, commentaire=f"{pack.code} — {commentaire_prix}".strip(" —"), utilisateur=created_by if getattr(created_by, "is_authenticated", False) else None)
            if record["pack"] and not changed_fields:
                stats["conditionnements_updated"] += 1
        elif record["pack"] and not changed_fields and record["target_price_changed"]:
            stats["conditionnements_updated"] += 1
    base = product.conditionnements.filter(facteur_conversion=1).order_by("-par_defaut", "pk").first()
    if base and (not modification or portee_prix == PRICE_SCOPE_GLOBAL):
        Produit.objects.filter(pk=product.pk).update(prix_vente=base.prix_vente)
    stats["product_id"] = product.pk
    stats["category_obj"] = category
    return stats


ZERO_PRICE = Decimal("0.00")


def _examples(english=False):
    yes, no = ("Yes", "No") if english else ("Oui", "Non")
    return [
        ["PEN001" if english else "STYLO001", "Blue pen" if english else "Stylo bleu", "BIE", "Supplies" if english else "Fournitures", "Piece" if english else "Pièce", "B", yes, "PEN001-U" if english else "STYLO001-U", "Piece" if english else "Pièce", 1, 1000, "3012345678901", yes, yes, yes, no, yes],
        *[["JUICE001" if english else "JUS001", "Orange juice 33cl" if english else "Jus Orange 33cl", "BIE", "Drinks" if english else "Boissons", "Bottle" if english else "Bouteille", "B", yes, ("JUICE001" if english else "JUS001") + suffix, label, factor, price, "3012345678918", yes, yes, yes if factor == 1 else no, no, yes]
          for suffix, label, factor, price in (("-U", "Bottle" if english else "Bouteille", 1, 1000), ("-P6", "Pack of 6" if english else "Paquet de 6", 6, 5500), ("-C24", "Carton of 24" if english else "Carton de 24", 24, 20000))],
    ]


def build_combined_workbook(*, products=None, pdv=None, modification=False, include_prices=True):
    """Modèle avec exemple ou export modifiable ; Produits et Aide - Help."""
    from .product_excel import _load_openpyxl
    Workbook, load_workbook_class, Font, PatternFill, DataValidation = _load_openpyxl()
    from openpyxl.styles import Alignment
    from openpyxl.utils import get_column_letter
    workbook = Workbook()
    sheet = workbook.active
    sheet.title = "Produits"
    fields = list(COMBINED_FIELDS)
    headers = [str(label) for label in COMBINED_HEADERS]
    if modification:
        fields = ["id_produit", "id_conditionnement"] + fields
        headers = [str(_("ID Produit")), str(_("ID conditionnement"))] + headers
    sheet.append(headers)
    sheet.freeze_panes = "C2" if modification else "B2"
    sheet.sheet_view.showGridLines = False
    fill, font = PatternFill("solid", fgColor="17365D"), Font(bold=True, color="FFFFFF")
    for cell in sheet[1]:
        cell.fill, cell.font, cell.alignment = fill, font, Alignment(wrap_text=True, vertical="center")
    sheet.row_dimensions[1].height = 32
    for index, field in enumerate(fields, 1):
        sheet.column_dimensions[get_column_letter(index)].width = 32 if field in ("nom", "libelle_conditionnement") else 23
        if field in ("code_sku", "code_conditionnement", "code_barres"):
            sheet.column_dimensions[get_column_letter(index)].number_format = "@"
        elif field in ("facteur_conversion", "prix_conditionnement"):
            sheet.column_dimensions[get_column_letter(index)].number_format = "0.000" if field == "facteur_conversion" else "0.00"
    has_sample = products is None and not modification
    if has_sample:
        from openpyxl.comments import Comment
        sheet.append(COMBINED_TEMPLATE_SAMPLE_ROW)
        sample_font = Font(italic=True, color="666666")
        sheet.row_dimensions[2].height = 24
        with override("fr"):
            for index, (col, example) in enumerate(zip(COMBINED_COLUMN_SPECS, COMBINED_TEMPLATE_SAMPLE_ROW), 1):
                cell = sheet.cell(2, index)
                cell.font = sample_font
                cell.alignment = Alignment(vertical="center")
                if col["field"] in ("code_sku", "code_conditionnement", "code_barres"):
                    cell.number_format = "@"
                elif col["field"] in ("facteur_conversion", "prix_conditionnement"):
                    cell.number_format = "0.000" if col["field"] == "facteur_conversion" else "0.00"
                sheet.cell(1, index).comment = Comment(
                    f"{col['description']}\n{col['english']}\n\n"
                    f"Obligatoire / Required : {'Oui / Yes' if col['required'] else 'Non / No'}\n"
                    f"Exemple / Example : {example}\n"
                    f"Valeurs autorisées / Allowed values : {col['allowed']}\n\n"
                    "Remplacez ou supprimez la ligne 2. L'exemple intact est ignoré à l'import.\n"
                    "Replace or delete row 2. The unchanged example is skipped during import.",
                    "FacControl", width=400, height=250,
                )
    if products is not None:
        packs = ConditionnementProduit.objects.filter(produit__in=products).select_related("produit__categorie", "produit__taxgroup", "produit__typeart").prefetch_related("prix_points_de_vente").order_by("produit__nom", "produit_id", "facteur_conversion", "pk")
        for pack in packs.iterator(chunk_size=500):
            product = pack.produit
            price = pack.prix_vente
            if pdv:
                price = next((local.prix_vente for local in pack.prix_points_de_vente.all() if local.point_de_vente_id == pdv.pk and local.actif), price)
            values = dict(id_produit=product.pk, id_conditionnement=pack.pk, code_sku=product.code_sku, nom=product.nom, typeart=product.typeart.code if product.typeart else "", categorie=product.categorie.nom if product.categorie else "", unite_mesure=product.unite_mesure, taxgroup=product.taxgroup.code if product.taxgroup else "", actif=product.actif, code_conditionnement=pack.code, libelle_conditionnement=pack.libelle, facteur_conversion=pack.facteur_conversion, prix_conditionnement=price if include_prices else None, code_barres=product.code_barres or "", vendable=pack.vendable, achetable=pack.achetable, par_defaut=pack.par_defaut, fractionnable=pack.fractionnable, actif_conditionnement=pack.actif)
            sheet.append([("Oui" if values[field] else "Non") if field in BOOL_DEFAULTS else values[field] for field in fields])
            for cell in sheet[sheet.max_row]:
                if isinstance(cell.value, str):
                    cell.data_type = "s"  # neutralise les formules injectées par un nom / code
                elif isinstance(cell.value, Decimal):
                    cell.number_format = "#,##0.000" if fields[cell.column - 1] == "facteur_conversion" else "#,##0.00"
    sheet.auto_filter.ref = f"A1:{get_column_letter(len(fields))}{max(sheet.max_row, 2)}"
    bool_validation = DataValidation(type="list", formula1='"Oui,Non,Yes,No,True,False,1,0"', allow_blank=True)
    bool_validation.errorTitle, bool_validation.error = str(_("Valeur invalide")), str(_("Utilisez Oui/Non ou Yes/No."))
    bool_validation.showErrorMessage = True
    sheet.add_data_validation(bool_validation)
    last_validation_row = MAX_DATA_ROWS + (2 if has_sample else 1)
    for index, field in enumerate(fields, 1):
        if field in BOOL_DEFAULTS:
            column = get_column_letter(index)
            bool_validation.add(f"{column}2:{column}{last_validation_row}")
    for field in ("facteur_conversion", "prix_conditionnement"):
        column = get_column_letter(fields.index(field) + 1)
        dv = DataValidation(type="decimal", operator="greaterThan" if field == "facteur_conversion" else "greaterThanOrEqual", formula1=0, allow_blank=True)
        dv.showErrorMessage = True
        sheet.add_data_validation(dv)
        dv.add(f"{column}2:{column}{last_validation_row}")
    help_sheet = workbook.create_sheet("Aide - Help")
    help_sheet.sheet_view.showGridLines = False
    help_sheet.append(["Champ / Field", "Français", "English", "Obligatoire / Required", "Exemple / Example", "Valeurs autorisées / Allowed values"])
    if modification:
        help_sheet.append(["ID Produit", "Identifiant interne en lecture seule ; doit correspondre au code produit.", "Read-only internal identifier; must match the product code.", "Non / No", "123", "Entier / Integer"])
        help_sheet.append(["ID conditionnement", "Identifiant historique en lecture seule ; permet de détecter un renommage de code utilisé.", "Read-only historical identifier; detects attempted renaming of a used code.", "Non / No", "456", "Entier / Integer"])
    # L'aide reste bilingue même si le téléchargement vient d'un écran anglais.
    # Résoudre les messages paresseux français sous leur langue, sans modifier
    # la langue de la feuille de saisie ni celle de la requête.
    with override("fr"):
        help_columns = [dict(col, header=str(col["header"]), description=str(col["description"])) for col in COMBINED_COLUMN_SPECS]
    for col in help_columns:
        help_sheet.append([col["header"], col["description"], col["english"], "Oui / Yes" if col["required"] else "Non / No", col["example"], col["allowed"]])
    help_sheet.append(["Règles / Rules", "Une ligne = Produit + Conditionnement. Informations générales identiques par code produit. Produit absent : création ; produit existant : mise à jour automatique à l'import. La modification en masse conserve sa confirmation. Aucune écriture de stock ni modification historique.", "One row = Product + Packaging. General fields must match for each product code. Import creates missing products and automatically updates existing products. Bulk editing retains its confirmation. No stock writes or historical changes."])
    help_sheet.append(["Défaut / Default", "À l'import, si aucun défaut actif n'est choisi, l'ancien défaut actif est conservé ou le plus petit facteur actif est sélectionné automatiquement.", "During import, if no active default is selected, the existing active default is kept or the smallest active factor is selected automatically."])
    help_sheet.append(["Modification / Editing", "Cellule vide = conserver l'existant en modification. Les ID sont en lecture seule. Prix local ou global selon la portée choisie. Facteurs et codes utilisés protégés.", "Blank cells keep existing values when editing. IDs are read-only. Prices are local or global according to selected scope. Used factors and codes are protected."])
    help_sheet.append(["Ancien format / Legacy", "Prix Vente + Unité Mesure + Groupe taxe restent compatibles : conditionnement facteur 1, vendable, achetable et par défaut.", "Sale Price + Unit of Measure + Tax Group remain compatible: base packaging factor 1, sellable, purchasable and default."])
    if has_sample:
        help_sheet.append(["Ligne d'exemple / Sample row", "La ligne 2 de Produits donne un exemple dans chaque colonne. Remplacez-la ou supprimez-la. L'exemple intact est ignoré à l'import. Survolez les en-têtes pour les indications de saisie. BIE et B sont des exemples : utilisez vos références DGI actives.", "Row 2 of Produits provides an example in every column. Replace or delete it. The unchanged example is skipped during import. Hover over the headers for entry instructions. BIE and B are examples: use your active DGI references."])
    for english in (False, True):
        help_sheet.append([])
        help_sheet.append(["Complete examples / Exemples complets — English" if english else "Exemples complets / Complete examples — Français"])
        example_rows = _examples(english)
        help_sheet.append(["Field / Champ", *[row[1] + " / " + row[8] for row in example_rows]])
        for index, col in enumerate(help_columns):
            help_sheet.append([col["header"], *[row[index] for row in example_rows]])
    for index, width in enumerate((27, 48, 48, 24, 25, 40), 1):
        help_sheet.column_dimensions[get_column_letter(index)].width = width
    for row in help_sheet:
        for cell in row:
            cell.alignment = Alignment(wrap_text=True, vertical="top")
        help_sheet.row_dimensions[row[0].row].height = 94 if str(row[0].value or "").startswith(("Règles", "Modification", "Ancien format", "Ligne d'exemple")) else (58 if 2 <= row[0].row <= 22 else 34)
    for cell in help_sheet[1]:
        cell.fill, cell.font = fill, font
    help_sheet.row_dimensions[1].height = 34
    help_sheet.freeze_panes = "B2"
    output = BytesIO()
    workbook.save(output)
    return output.getvalue()
