"""Documents de comptage ; les quantités officielles restent dans facturation."""

from decimal import Decimal, ROUND_HALF_UP

from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import IntegrityError, models, transaction
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils import timezone

QSTEP = Decimal("0.001")
VSTEP = Decimal("0.000000001")
MAX_STOCK = Decimal("9999999.999")
MOTIFS_NEGATIFS = {"CASSE", "PERTE", "VOL", "DETERIORATION", "ERREUR_SAISIE", "AUTRE"}
MOTIFS_POSITIFS = {"OUBLI_ENTREE", "ERREUR_HISTORIQUE", "STOCK_RETROUVE", "ERREUR_SAISIE", "AUTRE"}
MOTIF_CHOICES = (
    ("CASSE", "Casse"), ("PERTE", "Perte"), ("VOL", "Vol"),
    ("DETERIORATION", "Expiration / détérioration"), ("OUBLI_ENTREE", "Oubli d'entrée"),
    ("ERREUR_HISTORIQUE", "Erreur historique"), ("STOCK_RETROUVE", "Stock retrouvé"),
    ("ERREUR_SAISIE", "Erreur de saisie"), ("AUTRE", "Autre"),
)


class HistoriqueInventaireQuerySet(models.QuerySet):
    def delete(self):
        raise ValidationError("L'historique d'inventaire ne peut pas être supprimé en masse.")


class CompteurInventaireStock(models.Model):
    annee = models.PositiveIntegerField(primary_key=True)
    dernier_numero = models.PositiveIntegerField(default=0)

    @classmethod
    def prochain_numero(cls, annee):
        with transaction.atomic():
            try:
                compteur = cls.objects.select_for_update().get(annee=annee)
            except cls.DoesNotExist:
                try:
                    with transaction.atomic():
                        cls.objects.create(annee=annee)
                except IntegrityError:
                    pass
                compteur = cls.objects.select_for_update().get(annee=annee)
            compteur.dernier_numero += 1
            compteur.save(update_fields=["dernier_numero"])
            return compteur.dernier_numero


class InventaireStock(models.Model):
    STATUT_BROUILLON = "BROUILLON"
    STATUT_VALIDE = "VALIDE"
    STATUT_ANNULE = "ANNULE"
    STATUT_CHOICES = (("BROUILLON", "Brouillon"), ("VALIDE", "Validé"), ("ANNULE", "Annulé"))
    TYPE_CHOICES = (("COMPLET", "Complet — produits ayant du stock"), ("PARTIEL", "Partiel — sélection de produits"))

    numero = models.CharField(max_length=20, unique=True, editable=False)
    point_de_vente = models.ForeignKey("facturation.PointDeVente", on_delete=models.PROTECT, related_name="inventaires_stock")
    date_inventaire = models.DateField(default=timezone.localdate, db_index=True)
    type_inventaire = models.CharField(max_length=10, choices=TYPE_CHOICES, default="PARTIEL")
    masquer_theorique = models.BooleanField(default=False, verbose_name="Comptage à l'aveugle")
    statut = models.CharField(max_length=12, choices=STATUT_CHOICES, default="BROUILLON", editable=False, db_index=True)
    notes = models.TextField(blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, editable=False, related_name="inventaires_stock_crees")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    validated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, editable=False, related_name="inventaires_stock_valides")
    validated_at = models.DateTimeField(null=True, blank=True, editable=False)
    canceled_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, editable=False, related_name="inventaires_stock_annules")
    canceled_at = models.DateTimeField(null=True, blank=True, editable=False)
    objects = HistoriqueInventaireQuerySet.as_manager()

    class Meta:
        ordering = ("-date_inventaire", "-pk")
        constraints = [models.CheckConstraint(condition=models.Q(statut__in=["BROUILLON", "VALIDE", "ANNULE"]), name="inv_statut_valide")]

    def __str__(self):
        return self.numero or "Nouvel inventaire"

    @property
    def est_modifiable(self):
        return self.statut == self.STATUT_BROUILLON

    @transaction.atomic
    def save(self, *args, **kwargs):
        original = type(self).objects.select_for_update().filter(pk=self.pk).first() if self.pk else None
        if original:
            if self._state.adding or not original.est_modifiable:
                raise ValidationError("Un inventaire validé ou annulé est immuable.")
            for field in ("numero", "statut", "point_de_vente_id", "type_inventaire", "masquer_theorique", "created_by_id", "created_at", "validated_by_id", "validated_at", "canceled_by_id", "canceled_at"):
                if getattr(self, field) != getattr(original, field):
                    raise ValidationError("Le PDV, le périmètre, le mode de comptage et l'historique sont protégés.")
        elif self.statut != "BROUILLON" or any((self.validated_by_id, self.validated_at, self.canceled_by_id, self.canceled_at)):
            raise ValidationError("Créez un brouillon puis validez-le explicitement.")
        if not self.point_de_vente.actif:
            raise ValidationError("Le point de vente doit être actif.")
        self.full_clean(exclude=["numero"])
        if not original or self.date_inventaire.year != original.date_inventaire.year:
            self.numero = f"INV-{self.date_inventaire.year}-{CompteurInventaireStock.prochain_numero(self.date_inventaire.year):06d}"
            if kwargs.get("update_fields") is not None:
                kwargs["update_fields"] = set(kwargs["update_fields"]) | {"numero"}
        return super().save(*args, **kwargs)

    def valider(self, *, user=None):
        from .services_inventaires import valider_inventaire_stock
        return valider_inventaire_stock(self, user=user)

    @transaction.atomic
    def annuler(self, *, user=None):
        locked = type(self).objects.select_for_update().get(pk=self.pk)
        if not locked.est_modifiable:
            raise ValidationError("Seul un brouillon peut être annulé. Un inventaire validé exige une nouvelle correction tracée.")
        type(self).objects.filter(pk=self.pk).update(statut="ANNULE", canceled_by=user, canceled_at=timezone.now(), updated_at=timezone.now())
        self.refresh_from_db()
        return self

    def delete(self, *args, **kwargs):
        raise ValidationError("Un inventaire n'est jamais supprimé physiquement.")


class LigneInventaireStock(models.Model):
    inventaire = models.ForeignKey(InventaireStock, on_delete=models.PROTECT, related_name="lignes")
    produit = models.ForeignKey("facturation.Produit", on_delete=models.PROTECT, related_name="lignes_inventaire_stock")
    stock_source = models.ForeignKey("facturation.StockPointDeVente", on_delete=models.PROTECT, null=True, blank=True, editable=False, related_name="snapshots_inventaire")
    quantite_theorique_snapshot = models.DecimalField(max_digits=10, decimal_places=3, default=0, editable=False)
    cump_snapshot = models.DecimalField(max_digits=24, decimal_places=6, default=0, editable=False)
    cump_initialise_snapshot = models.BooleanField(default=False, editable=False)
    dernier_mouvement_snapshot = models.PositiveBigIntegerField(default=0, editable=False)
    snapshot_at = models.DateTimeField(editable=False)
    snapshot_revision = models.PositiveIntegerField(default=1, editable=False)
    quantite_comptee = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, editable=False)
    ecart = models.DecimalField(max_digits=11, decimal_places=3, null=True, blank=True, editable=False)
    cout_regularisation = models.DecimalField(max_digits=24, decimal_places=6, null=True, blank=True, editable=False, validators=[MinValueValidator(Decimal("0.000001"))])
    cout_utilise = models.DecimalField(max_digits=24, decimal_places=6, null=True, blank=True, editable=False)
    valeur_ecart = models.DecimalField(max_digits=27, decimal_places=9, default=0, editable=False)
    valeur_ecart_signee = models.DecimalField(max_digits=27, decimal_places=9, default=0, editable=False)
    motif = models.CharField(max_length=24, choices=MOTIF_CHOICES, blank=True)
    observation = models.TextField(blank=True)
    counted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, editable=False, related_name="lignes_inventaire_comptees")
    counted_at = models.DateTimeField(null=True, blank=True, editable=False)
    refreshed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, editable=False, related_name="lignes_inventaire_actualisees")
    regularized_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, editable=False, related_name="lignes_inventaire_valorisees")
    regularized_at = models.DateTimeField(null=True, blank=True, editable=False)
    objects = HistoriqueInventaireQuerySet.as_manager()

    class Meta:
        ordering = ("produit__nom", "pk")
        constraints = [
            models.UniqueConstraint(fields=["inventaire", "produit"], name="unique_produit_inventaire"),
            models.CheckConstraint(condition=models.Q(quantite_comptee__isnull=True) | models.Q(quantite_comptee__gte=0), name="inv_compte_non_negatif"),
        ]

    def __str__(self):
        return f"{self.inventaire.numero} / {self.produit.nom}"

    @transaction.atomic
    def save(self, *args, **kwargs):
        from .services_inventaires import capturer_snapshot
        self.inventaire = InventaireStock.objects.select_for_update().get(pk=self.inventaire_id)
        if not self.inventaire.est_modifiable:
            raise ValidationError("Les lignes de cet inventaire sont verrouillées.")
        original = type(self).objects.select_for_update().filter(pk=self.pk).first() if self.pk else None
        if original:
            if self._state.adding:
                raise ValidationError("Une ligne existante ne peut pas être remplacée.")
            for field in self._meta.fields:
                if field.name not in {"motif", "observation"} and getattr(self, field.attname) != getattr(original, field.attname):
                    raise ValidationError("Les snapshots et résultats nécessitent les actions de comptage/actualisation prévues.")
        else:
            if any((self.quantite_comptee is not None, self.ecart is not None, self.cout_regularisation is not None, self.cout_utilise is not None, self.valeur_ecart, self.valeur_ecart_signee, self.counted_by_id, self.counted_at)):
                raise ValidationError("Ajoutez le produit puis saisissez son comptage.")
            capturer_snapshot(self)
        self.full_clean()
        return super().save(*args, **kwargs)

    def actualiser(self, *, user=None):
        from .services_inventaires import actualiser_ligne_inventaire
        return actualiser_ligne_inventaire(self, user=user)

    def delete(self, *args, **kwargs):
        raise ValidationError("Une ligne d'inventaire doit être conservée ; annulez le document si nécessaire.")


class DetailComptageInventaire(models.Model):
    ligne = models.ForeignKey(LigneInventaireStock, on_delete=models.PROTECT, related_name="details_comptage")
    conditionnement = models.ForeignKey("facturation.ConditionnementProduit", on_delete=models.PROTECT, related_name="details_inventaire")
    conditionnement_libelle_snapshot = models.CharField(max_length=120, editable=False)
    facteur_snapshot = models.DecimalField(max_digits=12, decimal_places=3, editable=False)
    quantite_commerciale = models.DecimalField(max_digits=14, decimal_places=3, validators=[MinValueValidator(Decimal("0"))])
    quantite_physique = models.DecimalField(max_digits=10, decimal_places=3, editable=False)
    objects = HistoriqueInventaireQuerySet.as_manager()

    class Meta:
        ordering = ("pk",)
        constraints = [
            models.UniqueConstraint(fields=["ligne", "conditionnement"], name="unique_conditionnement_comptage"),
            models.CheckConstraint(condition=models.Q(quantite_commerciale__gte=0, quantite_physique__gte=0, facteur_snapshot__gt=0), name="inv_detail_quantites_valides"),
        ]

    @transaction.atomic
    def save(self, *args, **kwargs):
        from .services_inventaires import recalculer_comptage
        inventaire_id = LigneInventaireStock.objects.values_list("inventaire_id", flat=True).get(pk=self.ligne_id)
        inventaire = InventaireStock.objects.select_for_update().get(pk=inventaire_id)
        self.ligne = LigneInventaireStock.objects.select_for_update().get(pk=self.ligne_id)
        self.ligne.inventaire = inventaire
        if not inventaire.est_modifiable:
            raise ValidationError("Le comptage validé ou annulé est immuable.")
        original = type(self).objects.select_for_update().filter(pk=self.pk).first() if self.pk else None
        if original and (self._state.adding or original.ligne_id != self.ligne_id or original.conditionnement_id != self.conditionnement_id):
            raise ValidationError("La source du détail de comptage est protégée.")
        if self.conditionnement.produit_id != self.ligne.produit_id or not self.conditionnement.actif:
            raise ValidationError("Choisissez un conditionnement actif de ce produit.")
        self.conditionnement_libelle_snapshot = original.conditionnement_libelle_snapshot if original else self.conditionnement.libelle
        self.facteur_snapshot = original.facteur_snapshot if original else self.conditionnement.facteur_conversion
        self.quantite_physique = (Decimal(str(self.quantite_commerciale)) * self.facteur_snapshot).quantize(QSTEP, rounding=ROUND_HALF_UP)
        self.full_clean()
        result = super().save(*args, **kwargs)
        recalculer_comptage(self.ligne)
        return result

    @transaction.atomic
    def delete(self, *args, **kwargs):
        from .services_inventaires import recalculer_comptage
        inventaire_id = LigneInventaireStock.objects.values_list("inventaire_id", flat=True).get(pk=self.ligne_id)
        inventaire = InventaireStock.objects.select_for_update().get(pk=inventaire_id)
        ligne = LigneInventaireStock.objects.select_for_update().get(pk=self.ligne_id)
        if not inventaire.est_modifiable:
            raise ValidationError("Ce détail historisé est verrouillé.")
        result = super().delete(*args, **kwargs)
        recalculer_comptage(ligne)
        return result


@receiver(pre_delete, sender="facturation.MouvementStock", dispatch_uid="conserver_mouvement_inventaire")
def conserver_mouvement_inventaire(sender, instance, **kwargs):
    if instance.type_mouvement in {"INVENTAIRE_AJUSTEMENT_POSITIF", "INVENTAIRE_AJUSTEMENT_NEGATIF"}:
        raise ValidationError("Un ajustement d'inventaire ne peut pas être supprimé ; créez une nouvelle correction tracée.")
