"""Écritures Excel par lots, après validation de chaque groupe produit.

Les méthodes save() individuelles sont remplacées ici par leurs invariants
explicites : défaut unique, protection des historiques et prix de compatibilité.
Chaque lot est transactionnel ; un conflit est repris groupe par groupe.
"""

from collections import defaultdict
from copy import copy
from decimal import Decimal

from django.core.exceptions import FieldDoesNotExist, ValidationError
from django.db import transaction
from django.utils import timezone
from django.utils.translation import gettext as _

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


IMPORT_BATCH_SIZE = 250
WRITE_BATCH_SIZE = 500


def _related_ids(model, ids, relations):
    used = set()
    if not ids:
        return used
    for name in relations:
        try:
            relation = model._meta.get_field(name)
        except FieldDoesNotExist:
            continue
        field = relation.field.attname
        used.update(relation.related_model.objects.filter(**{field + "__in": ids}).order_by().values_list(field, flat=True))
    return used


def protected_catalogue_ids(product_ids, pack_ids):
    """Charge les protections en requêtes groupées, plutôt que par ligne."""
    used_packs = _related_ids(ConditionnementProduit, pack_ids, (
        "lignes_vente", "lignes_achat", "lignes_transfert_stock", "details_inventaire",
    ))
    if pack_ids:
        from achats.models import LigneRetourFournisseur
        used_packs.update(LigneRetourFournisseur.objects.filter(conditionnement_id__in=pack_ids).order_by().values_list("conditionnement_id", flat=True))
    used_products = _related_ids(Produit, product_ids, (
        "lignecommande", "lignes_achat", "lignes_transfert_stock", "lignes_inventaire_stock",
    ))
    if product_ids:
        used_products.update(StockPointDeVente.objects.filter(produit_id__in=product_ids).order_by().values_list("produit_id", flat=True))
    return used_products, used_packs


def prepare_group_packs(product, records, existing, *, modification=False, portee_prix=PRICE_SCOPE_GLOBAL):
    """Calcule l'état final complet avant toute écriture ou démotion du défaut."""
    from .product_excel_conditionnements import PACK_FIELDS

    final = {pack.pk: copy(pack) for pack in existing}
    prepared = []
    for record in records:
        source = record["pack"]
        key = source.pk if source else -record["row"]
        if source and key not in final:
            raise ValidationError({"code_conditionnement": _("Le conditionnement a changé pendant l'import. Relancez le fichier.")})
        pack = final[key] if source else ConditionnementProduit(produit=product)
        for field, value in record["pack_values"].items():
            if not (source and modification and portee_prix == PRICE_SCOPE_PDV and field == "prix_vente"):
                setattr(pack, field, value)
        final[key] = pack
        prepared.append((record, pack))
    chosen = next((record for record in records if record["pack_values"]["par_defaut"] and record["pack_values"]["actif"]), None)
    if chosen:
        chosen_key = chosen["pack"].pk if chosen["pack"] else -chosen["row"]
        for key, pack in final.items():
            if key != chosen_key and pack.actif:
                pack.par_defaut = False
    active = [pack for pack in final.values() if pack.actif]
    defaults = [pack for pack in active if pack.par_defaut]
    if not defaults and active and (not modification or (not product.pk and not any(record["default_specified"] for record in records))):
        # Un import crée ou met à jour une fiche utilisable même sans choix
        # explicite : garder l'ancien défaut actif, sinon le plus petit facteur.
        previous_defaults = {pack.pk for pack in existing if pack.par_defaut and pack.actif}
        preferred = [pack for pack in active if pack.pk in previous_defaults]
        chosen_pack = min(preferred or active, key=lambda pack: (pack.facteur_conversion, pack.code))
        chosen_pack.par_defaut = True
        defaults = [chosen_pack]
    if len(defaults) > 1:
        raise ValidationError({"par_defaut": _("Le produit %(sku)s possède plusieurs conditionnements actifs par défaut : %(codes)s. Conservez « Oui » sur un seul et mettez « Non » sur les autres.") % {"sku": product.code_sku, "codes": ", ".join(pack.code for pack in defaults)}})
    if product.actif and not defaults:
        raise ValidationError({"par_defaut": _("Aucun conditionnement actif n'est choisi par défaut pour le produit %(sku)s. Mettez « Oui » dans la colonne « Par défaut » d'un seul conditionnement actif, puis relancez l'import.") % {"sku": product.code_sku}})
    original = {pack.pk: pack for pack in existing}
    changes = [(pack, [field for field in PACK_FIELDS.values() if getattr(original[pack.pk], field) != getattr(pack, field)]) for pack in final.values() if pack.pk]
    return final, prepared, [(pack, fields) for pack, fields in changes if fields]


def apply_import_batch(plans, category_cache, *, created_by, modification, pdv, portee_prix, target_points, commentaire_prix=""):
    """Persiste un lot validé avec un nombre de requêtes proportionnel aux lots."""
    from .product_excel import _normalize_lookup_text, _normalize_sku

    stats = dict(created=0, updated=0, unchanged_products=0, categories_created=0, conditionnements_created=0, conditionnements_updated=0, point_prices_created=0, point_prices_updated=0)
    now = timezone.now()
    with transaction.atomic():
        ids = [product.pk for product, records in plans if product]
        locked_products = {product.pk: product for product in Produit.objects.select_for_update().filter(pk__in=ids).select_related("categorie", "typeart", "taxgroup").order_by("pk")}
        locked_packs = list(ConditionnementProduit.objects.select_for_update().filter(produit_id__in=ids).order_by("pk"))
        packs_by_product = defaultdict(list)
        for pack in locked_packs:
            packs_by_product[pack.produit_id].append(pack)
        used_products, used_packs = protected_catalogue_ids(ids, [pack.pk for pack in locked_packs])
        points = list(target_points)
        old_local = {(price.conditionnement_id, price.point_de_vente_id): price for price in ProduitPointVentePrix.objects.select_for_update().filter(conditionnement_id__in=[pack.pk for pack in locked_packs], point_de_vente__in=points).order_by("pk")}
        categories = category_cache.copy()
        new_categories = {}
        for source, records in plans:
            name = records[0]["product_values"]["categorie"]
            key = _normalize_lookup_text(name)
            if name and key not in categories:
                categories[key] = new_categories[key] = Categorie(nom=name)
        Categorie.objects.bulk_create(list(new_categories.values()), batch_size=WRITE_BATCH_SIZE)
        if new_categories and any(category.pk is None for category in new_categories.values()):
            for category in Categorie.objects.filter(nom__in=[category.nom for category in new_categories.values()]).order_by("pk"):
                categories[_normalize_lookup_text(category.nom)] = category
        stats["categories_created"] = len(new_categories)
        new_products, groups = [], []
        product_updates, pack_updates = defaultdict(list), defaultdict(list)
        new_packs, history_rows = [], []
        historical_pack_ids = set()
        updated_product_ids = set()
        original_global_prices = {pack.pk: pack.prix_vente for pack in locked_packs}
        for source, records in plans:
            values = records[0]["product_values"].copy()
            category_name = values.pop("categorie")
            values["categorie"] = categories.get(_normalize_lookup_text(category_name)) if category_name else None
            if source:
                if source.pk not in locked_products:
                    raise ValidationError({"code_sku": _("Le produit a changé pendant l'import. Relancez le fichier.")})
                product = copy(locked_products[source.pk])
                if _normalize_lookup_text(product.unite_mesure) != _normalize_lookup_text(values["unite_mesure"]) and product.pk in used_products:
                    raise ValidationError({"unite_mesure": _("L'unité de base est protégée : ce produit possède du stock ou un historique.")})
                changed_fields = [field for field, value in values.items() if getattr(product, field) != value]
                for field, value in values.items():
                    setattr(product, field, value)
            else:
                product = Produit(code_sku=records[0]["sku"], prix_vente=Decimal("0.00"), created_by=created_by, **values)
                changed_fields = []
                new_products.append(product)
            existing = packs_by_product.get(product.pk, [])
            original = {pack.pk: pack for pack in existing}
            final, prepared, pack_changes = prepare_group_packs(product, records, existing, modification=modification, portee_prix=portee_prix)
            for record, pack in prepared:
                if record["pack"]:
                    old = original[pack.pk]
                    if (old.code != pack.code or old.facteur_conversion != pack.facteur_conversion) and pack.pk in used_packs:
                        raise ValidationError({"facteur_conversion": _("Facteur ou code historique utilisé protégé. Désactivez ce conditionnement et créez-en un nouveau.")})
                    local = old_local.get((pack.pk, pdv.pk)) if pdv else None
                    old_price = local.prix_vente if portee_prix == PRICE_SCOPE_PDV and local and local.actif else old.prix_vente
                    if modification and old_price != record["pack_values"]["prix_vente"]:
                        history_rows.append((product, pack, old_price, record["pack_values"]["prix_vente"]))
                        historical_pack_ids.add(pack.pk)
                else:
                    new_packs.append(pack)
            bases = [pack for pack in final.values() if pack.facteur_conversion == Decimal("1")]
            if bases and (not modification or portee_prix == PRICE_SCOPE_GLOBAL):
                base = min(bases, key=lambda pack: (not pack.par_defaut, pack.pk if pack.pk else float("inf")))
                if product.prix_vente != base.prix_vente:
                    changed_fields.append("prix_vente")
                product.prix_vente = base.prix_vente
            if source and changed_fields:
                product.update_at = now
                product_updates[tuple(sorted(changed_fields))].append(product)
            if source and (changed_fields or pack_changes or any(not record["pack"] for record in records)):
                updated_product_ids.add(product.pk)
            for pack, fields in pack_changes:
                pack.updated_at = now
                pack_updates[tuple(sorted(fields))].append(pack)
            stats["conditionnements_updated"] += len(pack_changes)
            groups.append((product, records, prepared, {pack.pk for pack, fields in pack_changes}))
        Produit.objects.bulk_create(new_products, batch_size=WRITE_BATCH_SIZE)
        if new_products and any(product.pk is None for product in new_products):
            new_by_sku = {_normalize_sku(product.code_sku): product.pk for product in Produit.objects.filter(code_sku__in=[product.code_sku for product in new_products]).order_by().only("pk", "code_sku")}
            for product in new_products:
                product.pk = new_by_sku[_normalize_sku(product.code_sku)]
        for fields, products in product_updates.items():
            Produit.objects.bulk_update(products, [*fields, "update_at"], batch_size=WRITE_BATCH_SIZE)
        stats["created"] = len(new_products)
        for product, records, prepared, changed_ids in groups:
            for record, pack in prepared:
                pack.produit = product
        ConditionnementProduit.objects.bulk_create(new_packs, batch_size=WRITE_BATCH_SIZE)
        if new_packs and any(pack.pk is None for pack in new_packs):
            new_by_code = {_normalize_sku(pack.code): pack.pk for pack in ConditionnementProduit.objects.filter(code__in=[pack.code for pack in new_packs]).order_by().only("pk", "code")}
            for pack in new_packs:
                pack.pk = new_by_code[_normalize_sku(pack.code)]
        for fields, packs in pack_updates.items():
            ConditionnementProduit.objects.bulk_update(packs, [*fields, "updated_at"], batch_size=WRITE_BATCH_SIZE)
        stats["conditionnements_created"] = len(new_packs)
        new_prices, changed_prices = [], []
        global_price_changes = defaultdict(list)
        for product, records, prepared, changed_ids in groups:
            for record, pack in prepared:
                price = record["pack_values"]["prix_vente"]
                source = record["pack"]
                if modification and portee_prix == PRICE_SCOPE_GLOBAL and source and original_global_prices[pack.pk] != price:
                    global_price_changes[price].append(pack.pk)
                local_changed = False
                for point in points:
                    local = old_local.get((pack.pk, point.pk)) if source else None
                    if local and local.prix_vente == price and local.actif and local.produit_id == product.pk:
                        continue
                    if local:
                        local.prix_vente, local.actif, local.produit_id, local.updated_at = price, True, product.pk, now
                        changed_prices.append(local)
                    else:
                        new_prices.append(ProduitPointVentePrix(produit=product, conditionnement=pack, point_de_vente=point, prix_vente=price, actif=True))
                    local_changed = True
                has_history = pack.pk in historical_pack_ids
                if source and pack.pk not in changed_ids and (local_changed or has_history):
                    stats["conditionnements_updated"] += 1
                if source and (local_changed or has_history):
                    updated_product_ids.add(product.pk)
        for price, pack_ids in global_price_changes.items():
            ProduitPointVentePrix.objects.filter(conditionnement_id__in=pack_ids).update(prix_vente=price)
        ProduitPointVentePrix.objects.bulk_create(new_prices, batch_size=WRITE_BATCH_SIZE)
        ProduitPointVentePrix.objects.bulk_update(changed_prices, ["prix_vente", "actif", "produit", "updated_at"], batch_size=WRITE_BATCH_SIZE)
        stats["point_prices_created"], stats["point_prices_updated"] = len(new_prices), len(changed_prices)
        stats["updated"] = len(updated_product_ids)
        stats["unchanged_products"] = len(ids) - stats["updated"]
        HistoriquePrixProduit.objects.bulk_create([
            HistoriquePrixProduit(produit=product, ancien_prix=old, nouveau_prix=new, 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)
            for product, pack, old, new in history_rows
        ], batch_size=WRITE_BATCH_SIZE)
    category_cache.update(categories)
    return stats, {product.pk for product, records, prepared, changed_ids in groups}
