"""
Moteur des rapports fiscaux DGI au format e-UF (X, Z, P et A).

- X : recapitulatif de la session en cours depuis le dernier Z, sans remise a zero ;
- Z : meme recapitulatif, puis cloture de la session (remise a zero) ;
- P : rapport X sur une periode choisie, sans remise a zero ;
- A : recapitulatif par article depuis le dernier A, puis remise a zero.

Les sessions Z et A sont tenues par point de vente : un rapport portant sur
plusieurs points de vente cumule les sessions de chacun et, pour Z et A,
cloture chaque point de vente avec son propre numero.

Seuls les documents portant des elements de securite DGI sont comptes dans
les montants ; les autres sont signales comme factures incompletes. Chaque
document compte a sa date de normalisation et pour les montants enregistres
par la DGI (e-MCF/MCF), comme dans les releves de la DGI.
"""

from collections import OrderedDict
from dataclasses import dataclass
from datetime import datetime, time
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from functools import reduce
import operator

from django.db import transaction
from django.db.models import BooleanField, Case, Count, Max, Min, Q, Sum, Value, When
from django.utils import timezone
from django.utils.translation import gettext

from dgi.models import TaxGroup
from facturation.access_control import get_accessible_point_de_vente_queryset
from facturation.accounting import FISCAL_DATE_ALIAS, FISCAL_TTC_ALIAS, with_fiscal_reference
from facturation.fiscal_amounts import fiscal_ttc, fiscal_tva
from facturation.fiscal_rules import (
    compute_invoice_tax_totals,
    compute_line_tax_breakdown,
    compute_product_specific_tax_amount,
    get_tax_group_rule,
)
from facturation.models import Commande, Configuration, PointDeVente

from .models import ClotureFiscaleDGI, RapportFiscalDGI


MONEY_STEP = Decimal("0.01")
ZERO = Decimal("0")

INVOICE_TYPES = ("FV", "FT", "FA", "EV", "ET", "EA")
CREDIT_NOTE_TYPES = frozenset({"FA", "EA"})
TAX_GROUP_CODES = tuple("ABCDEFGHIJKLMNOPQRS")
PAYMENT_TYPES = (
    ("ESPECES", "ESPECES"),
    ("MOBILE_MONEY", "MOBILE MONEY"),
    ("CHEQUES", "CHEQUES"),
    ("CARTE_BANCAIRE", "CARTE BANCAIRE"),
    ("VIREMENT", "VIREMENT"),
    ("AUTRE_1", "AUTRE 1"),
    ("AUTRE_2", "AUTRE 2"),
)

KIND_X = "X"
KIND_Z = RapportFiscalDGI.TYPE_Z
KIND_P = "P"
KIND_A = RapportFiscalDGI.TYPE_A

DISPLAY_DATETIME = "%d/%m/%Y %H:%M:%S"

# Un document est complet des qu'il porte un element de securite DGI/MCF.
SECURITY_FIELDS = ("codedefdgi", "uid", "qrCode", "nim", "counters", "dateTimedgi")
FISCALISE_Q = reduce(
    operator.or_,
    (Q(**{f"{field}__isnull": False}) & ~Q(**{field: ""}) for field in SECURITY_FIELDS),
)


def _decimal(value):
    """Convertit une valeur libre en Decimal exploitable par les calculs."""

    try:
        return Decimal(str(value or 0))
    except (InvalidOperation, TypeError, ValueError):
        return ZERO


def _money(value):
    """Normalise un montant monetaire sur deux decimales."""

    return _decimal(value).quantize(MONEY_STEP, rounding=ROUND_HALF_UP)


def _display(value):
    """Formate une date locale pour l'en-tete du rapport (fige dans le contenu)."""

    if not value:
        return ""
    return timezone.localtime(value).strftime(DISPLAY_DATETIME)


def _document_type(commande):
    """Retourne le type de document DGI transmis lors de la fiscalisation."""

    code = str(getattr(commande, "type_facture", "") or "FV").strip().upper()
    return code if code in INVOICE_TYPES else "FV"


def payment_bucket(code, designation=""):
    """Classe un mode de paiement local dans une des sept rubriques DGI."""

    for raw in (code, designation):
        key = "".join(ch for ch in str(raw or "").upper() if ch.isalnum())
        if not key:
            continue
        if key in {"E", "CASH"} or key.startswith("ESPECE"):
            return "ESPECES"
        if key == "M" or "MOBILE" in key or "MONEY" in key or "MPESA" in key:
            return "MOBILE_MONEY"
        if key == "D" or "CHEQUE" in key:
            return "CHEQUES"
        if key in {"C", "CB"} or "CARTE" in key:
            return "CARTE_BANCAIRE"
        if key == "V" or "VIREMENT" in key or "BANQUE" in key:
            return "VIREMENT"
        if key == "AUTRE2":
            return "AUTRE_2"
    return "AUTRE_1"


# ---------------------------------------------------------------------------
# Selection des points de vente
# ---------------------------------------------------------------------------

def resolve_points_selection(user, raw_values):
    """
    Resout la selection multiple de points de vente dans le perimetre autorise.

    Sans selection explicite, on retient le point de vente de l'utilisateur
    lorsqu'il en a un, sinon tous ses points de vente autorises.
    """

    accessible = list(get_accessible_point_de_vente_queryset(user))
    by_id = {point.pk: point for point in accessible}
    values = [str(value).strip() for value in raw_values if str(value or "").strip()]
    errors = []
    explicit_all = "all" in values

    if not accessible:
        errors.append(gettext("Aucun point de vente n'est autorisé pour votre compte."))
        selected = []
    elif explicit_all:
        selected = list(accessible)
    elif values:
        requested = []
        for value in values:
            try:
                requested.append(int(value))
            except ValueError:
                errors.append(gettext("Filtre point de vente invalide."))
        if any(point_id not in by_id for point_id in requested):
            errors.append(gettext("Un des points de vente sélectionnés n'est pas autorisé pour votre compte."))
        wanted = set(requested)
        selected = [point for point in accessible if point.pk in wanted]
    else:
        own = by_id.get(getattr(user, "point_de_vente_id", None))
        selected = [own] if own else list(accessible)

    covers_all = bool(accessible) and len(selected) == len(accessible)
    return {
        "accessible": accessible,
        "points": selected,
        "ids": [point.pk for point in selected],
        "errors": errors,
        "can_select_all": len(accessible) > 1,
        "widget_values": ["all"] if covers_all and len(accessible) > 1 else [point.pk for point in selected],
    }


# ---------------------------------------------------------------------------
# Sessions Z / A
# ---------------------------------------------------------------------------

@dataclass
class PeriodePoint:
    """Perimetre d'un point de vente dans un rapport."""

    point_de_vente: PointDeVente
    fin: datetime
    debut: datetime = None
    debut_exclusif: bool = True
    debut_affiche: datetime = None
    numero: int = None

    def as_q(self):
        """Filtre ORM des documents du point de vente sur sa periode."""

        conditions = {"point_de_vente_id": self.point_de_vente.pk, f"{FISCAL_DATE_ALIAS}__lte": self.fin}
        if self.debut is not None:
            lookup = "gt" if self.debut_exclusif else "gte"
            conditions[f"{FISCAL_DATE_ALIAS}__{lookup}"] = self.debut
        return Q(**conditions)


def build_session_periods(points, type_rapport, fin=None):
    """
    Construit la session en cours (depuis la derniere cloture) de chaque point de vente.

    `numero` est le numero qu'aura la prochaine cloture de ce type.
    """

    fin = fin or timezone.now()
    last_closures = {
        row["point_de_vente_id"]: row
        for row in ClotureFiscaleDGI.objects.filter(type_rapport=type_rapport, point_de_vente__in=points)
        .values("point_de_vente_id")
        .annotate(numero=Max("numero"), fin=Max("date_fin"))
    }
    never_closed = [point.pk for point in points if point.pk not in last_closures]
    first_documents = {}
    if never_closed:
        first_documents = dict(
            Commande.objects.filter(point_de_vente_id__in=never_closed)
            .values("point_de_vente_id")
            .annotate(first=Min("date_commande"))
            .values_list("point_de_vente_id", "first")
        )

    periods = []
    for point in points:
        last = last_closures.get(point.pk)
        debut = last["fin"] if last else None
        periods.append(
            PeriodePoint(
                point_de_vente=point,
                fin=fin,
                debut=debut,
                debut_affiche=debut or first_documents.get(point.pk) or point.created_at,
                numero=(last["numero"] if last else 0) + 1,
            )
        )
    return periods


def build_custom_periods(points, date_debut, date_fin):
    """Construit une periode identique pour chaque point de vente (rapport periodique)."""

    debut = timezone.make_aware(datetime.combine(date_debut, time.min))
    fin = timezone.make_aware(datetime.combine(date_fin, time.max))
    return [
        PeriodePoint(point_de_vente=point, fin=fin, debut=debut, debut_exclusif=False, debut_affiche=debut)
        for point in points
    ]


def _periods_q(periods):
    """Combine les perimetres de plusieurs points de vente."""

    if not periods:
        return Q(pk__in=[])
    return reduce(operator.or_, (period.as_q() for period in periods))


def last_document_dates(point_ids):
    """Date de la derniere facture enregistree de chaque point de vente, toutes periodes confondues."""

    return dict(
        Commande.objects.filter(point_de_vente_id__in=point_ids)
        .values("point_de_vente_id")
        .annotate(last=Max("date_commande"))
        .values_list("point_de_vente_id", "last")
    )


def summarize_periods(periods):
    """Resume chaque session : nombre de documents et montant net des documents complets."""

    totals = {period.point_de_vente.pk: {"nombre": 0, "montant": ZERO} for period in periods}
    last_dates = last_document_dates([period.point_de_vente.pk for period in periods]) if periods else {}
    if periods:
        rows = (
            with_fiscal_reference(Commande.objects.all())
            .filter(_periods_q(periods))
            .values("point_de_vente_id", "type_facture")
            .annotate(nombre=Count("id"), montant=Sum(FISCAL_TTC_ALIAS, filter=FISCALISE_Q))
        )
        for row in rows:
            entry = totals[row["point_de_vente_id"]]
            sign = -1 if str(row["type_facture"] or "").upper() in CREDIT_NOTE_TYPES else 1
            entry["nombre"] += row["nombre"]
            entry["montant"] += sign * _decimal(row["montant"])

    summary = []
    for period in periods:
        entry = totals[period.point_de_vente.pk]
        summary.append(
            {
                "point_de_vente": period.point_de_vente,
                "numero": period.numero,
                "debut": period.debut_affiche,
                "deja_cloture": period.debut is not None,
                "derniere_facture": last_dates.get(period.point_de_vente.pk),
                "nombre_factures": entry["nombre"],
                "montant_total": _money(entry["montant"]),
            }
        )
    return summary


# ---------------------------------------------------------------------------
# Calcul du contenu e-UF
# ---------------------------------------------------------------------------

def _empty_amounts():
    """Initialise un cumul de montants DGI."""

    return {"total": ZERO, "ht": ZERO, "tva": ZERO, "taxe_specifique": ZERO}


def _load_documents(periods):
    """Charge les documents du perimetre avec leurs lignes et paiements."""

    return list(
        with_fiscal_reference(Commande.objects.all())
        .filter(_periods_q(periods))
        .annotate(est_fiscalise=Case(When(FISCALISE_Q, then=Value(True)), default=Value(False), output_field=BooleanField()))
        .select_related("point_de_vente")
        .prefetch_related("lignes__produit__taxgroup", "paiements__mode_paiement")
        .order_by(FISCAL_DATE_ALIAS, "numero")
    )


def _line_details(commande, default_mode_dgi, tax_rates):
    """Ventile les lignes d'un document par groupe de taxation, remise globale incluse."""

    mode_dgi = str(getattr(commande, "mode_dgi", "") or default_mode_dgi or "ttc").strip().lower()
    lines = []
    for ligne in commande.lignes.all():
        produit = ligne.produit
        product_group = getattr(produit, "taxgroup", None)
        code = (
            str(getattr(ligne, "groupe_taxation_snapshot", "") or "").strip().upper()
            or str(getattr(product_group, "code", "") or "").strip().upper()
            or "A"
        )
        if code in tax_rates:
            rate = tax_rates[code]
        else:
            rate = _decimal(getattr(product_group, "tax", 0))
        breakdown = compute_line_tax_breakdown(
            subtotal=ligne.sous_total,
            tax_rate=rate,
            mode_dgi=mode_dgi,
            tax_group_code=code,
            specific_tax_amount=compute_product_specific_tax_amount(produit, ligne.sous_total, ligne.quantite),
        )
        lines.append({"ligne": ligne, "code": code, "rate": rate, "breakdown": breakdown})

    remise_globale = _decimal(getattr(commande, "remise_globale", 0))
    ratio = Decimal("1")
    if remise_globale > 0:
        ratio = compute_invoice_tax_totals([line["breakdown"] for line in lines], remise_globale)["discount_ratio"]
    return lines, ratio, mode_dgi


def _line_tax_reduction(remise, rate, code, mode_dgi):
    """Part de TVA contenue dans une remise de ligne."""

    remise = _decimal(remise)
    if remise <= 0 or rate <= 0 or get_tax_group_rule(code)["vat_mode"] != "rate":
        return ZERO
    if mode_dgi == "ttc":
        return remise * rate / (Decimal("100") + rate)
    return remise * rate / Decimal("100")


def _allocate(amount, weights):
    """Repartit un montant au centime pres au prorata des poids ; l'arrondi va a la plus grosse part."""

    if not weights:
        return []
    total_weight = sum(weights, ZERO)
    if not total_weight:
        return [amount] + [ZERO] * (len(weights) - 1)
    parts = [_money(amount * weight / total_weight) for weight in weights]
    remainder = amount - sum(parts, ZERO)
    if remainder:
        parts[max(range(len(weights)), key=lambda index: abs(weights[index]))] += remainder
    return parts


def _invoice_group_amounts(commande, lines, ratio):
    """
    Montants de la facture par groupe de taxation.

    Les montants par groupe enregistres par la DGI font foi. A defaut, le TTC
    et la TVA normalises de la facture sont ventiles entre groupes au prorata
    des lignes, pour que le rapport retombe exactement sur la DGI.
    """

    groups = OrderedDict()
    for line in lines:
        breakdown = line["breakdown"]
        entry = groups.setdefault(line["code"], {"ttc": ZERO, "tva": ZERO, "specifique": ZERO})
        entry["ttc"] += _decimal(breakdown["ttc_amount"]) * ratio
        entry["tva"] += _decimal(breakdown["tax_amount"]) * ratio
        entry["specifique"] += _decimal(breakdown["specific_tax_amount"]) * ratio
    if not groups:
        groups["A"] = {"ttc": ZERO, "tva": ZERO, "specifique": ZERO}

    fiscal_groups = ((getattr(commande, "fiscal_details", None) or {}).get("groups") or {})
    if fiscal_groups:
        line_ttc = sum((entry["ttc"] for entry in groups.values()), ZERO)
        fiscal_total = _money(fiscal_ttc(commande))
        scale = fiscal_total / line_ttc if line_ttc else ZERO
        result = OrderedDict()
        for code in sorted(fiscal_groups):
            values = fiscal_groups[code]
            total = _money(values.get("ttc"))
            tva = _money(values.get("tva"))
            specifique = _money((groups.get(code) or {}).get("specifique", ZERO) * scale)
            result[str(code).upper()] = {"total": total, "ht": total - tva - specifique, "tva": tva, "taxe_specifique": specifique}
        return result

    codes = list(groups)
    ttc_weights = [groups[code]["ttc"] for code in codes]
    tva_weights = [groups[code]["tva"] for code in codes]
    invoice_ttc = _money(fiscal_ttc(commande))
    computed_ttc = sum(ttc_weights, ZERO)
    scale = invoice_ttc / computed_ttc if computed_ttc else ZERO

    ttc_parts = _allocate(invoice_ttc, ttc_weights)
    tva_parts = _allocate(_money(fiscal_tva(commande)), tva_weights if any(tva_weights) else ttc_weights)
    result = OrderedDict()
    for index, code in enumerate(codes):
        specifique = _money(groups[code]["specifique"] * scale)
        result[code] = {
            "total": ttc_parts[index],
            "ht": ttc_parts[index] - tva_parts[index] - specifique,
            "tva": tva_parts[index],
            "taxe_specifique": specifique,
        }
    return result


def _document_payments(commande, sign):
    """
    Paiements d'un document, ramenes a son total : la monnaie rendue est
    deduite des especes. Sans paiement, le total est compte en especes
    (comme a la fiscalisation).
    """

    total = _money(fiscal_ttc(commande))
    payments = []
    for paiement in commande.paiements.all():
        mode = getattr(paiement, "mode_paiement", None)
        bucket = payment_bucket(getattr(mode, "code", "") or paiement.mode_paiement_id, getattr(mode, "designation", ""))
        payments.append([bucket, _decimal(paiement.montant)])
    if not payments:
        return [("ESPECES", sign * total)]

    excess = sum((amount for _bucket, amount in payments), ZERO) - total
    for payment in sorted(payments, key=lambda item: item[0] != "ESPECES"):
        if excess <= 0:
            break
        deduction = min(payment[1], excess)
        payment[1] -= deduction
        excess -= deduction
    return [(bucket, sign * amount) for bucket, amount in payments]


def compute_report_content(periods, kind, generated_at=None, user=None):
    """
    Calcule le contenu complet d'un rapport e-UF pour les perimetres donnes.

    Le resultat ne contient que des chaines, entiers, booleens et Decimal : il
    peut etre fige tel quel dans `RapportFiscalDGI.contenu`.
    """

    generated_at = generated_at or timezone.now()
    config = Configuration.objects.first()
    default_mode_dgi = getattr(config, "mode_dgi", "ttc")
    tax_rates = {code.upper(): _decimal(rate) for code, rate in TaxGroup.objects.values_list("code", "tax")}
    documents = _load_documents(periods)

    types = OrderedDict(
        (code, {"code": code, "nombre": 0, "incompletes": 0, **_empty_amounts(), "groupes": OrderedDict()})
        for code in INVOICE_TYPES
    )
    payments = OrderedDict((code, ZERO) for code, _label in PAYMENT_TYPES)
    reductions = OrderedDict((code, {"montant": ZERO, "impot": ZERO}) for code in INVOICE_TYPES)
    articles = OrderedDict()
    per_point = {period.point_de_vente.pk: {"nombre": 0, "montant": ZERO} for period in periods}

    for commande in documents:
        type_code = _document_type(commande)
        type_entry = types[type_code]
        type_entry["nombre"] += 1
        per_point[commande.point_de_vente_id]["nombre"] += 1
        if not commande.est_fiscalise:
            type_entry["incompletes"] += 1
            continue

        is_credit = type_code in CREDIT_NOTE_TYPES
        sign = -1 if is_credit else 1
        lines, ratio, mode_dgi = _line_details(commande, default_mode_dgi, tax_rates)
        for code, amounts in _invoice_group_amounts(commande, lines, ratio).items():
            group = type_entry["groupes"].setdefault(code, _empty_amounts())
            for key, value in amounts.items():
                group[key] += value

        for line in lines:
            ligne = line["ligne"]
            reductions[type_code]["montant"] += _decimal(ligne.remise)
            reductions[type_code]["impot"] += _line_tax_reduction(ligne.remise, line["rate"], line["code"], mode_dgi)

            if kind == KIND_A:
                produit = ligne.produit
                prix = _money(ligne.prix_unitaire)
                key = (produit.code_sku, produit.nom, prix, line["code"])
                article = articles.setdefault(
                    key,
                    {"code": produit.code_sku, "designation": produit.nom, "prix": prix,
                     "groupe": line["code"], "qte_vendue": ZERO, "qte_retournee": ZERO},
                )
                article["qte_retournee" if is_credit else "qte_vendue"] += _decimal(ligne.quantite)

        remise_globale = _decimal(getattr(commande, "remise_globale", 0))
        if remise_globale > 0:
            gross_vat = sum((_decimal(line["breakdown"]["tax_amount"]) for line in lines), ZERO)
            reductions[type_code]["montant"] += remise_globale
            reductions[type_code]["impot"] += gross_vat * (Decimal("1") - ratio)

        for bucket, amount in _document_payments(commande, sign):
            payments[bucket] += amount
        per_point[commande.point_de_vente_id]["montant"] += sign * _money(fiscal_ttc(commande))

    sections_types = []
    for type_entry in types.values():
        extra_codes = sorted(code for code in type_entry["groupes"] if code not in TAX_GROUP_CODES)
        groupes = []
        for code in TAX_GROUP_CODES + tuple(extra_codes):
            amounts = {key: _money(value) for key, value in type_entry["groupes"].get(code, _empty_amounts()).items()}
            groupes.append({"code": code, **amounts, "non_nul": any(amounts.values())})
            for key, value in amounts.items():
                type_entry[key] += value
        sections_types.append(
            {
                "code": type_entry["code"],
                "nombre": type_entry["nombre"],
                "incompletes": type_entry["incompletes"],
                "total": _money(type_entry["total"]),
                "ht": _money(type_entry["ht"]),
                "tva": _money(type_entry["tva"]),
                "taxe_specifique": _money(type_entry["taxe_specifique"]),
                "groupes": groupes,
                "groupes_non_nuls": [groupe for groupe in groupes if groupe["non_nul"]],
                "a_montants": any(groupe["non_nul"] for groupe in groupes),
            }
        )

    articles_rows = []
    for index, article in enumerate(articles.values(), start=1):
        # Deux decimales comme le e-UF, trois seulement si une quantite fractionnee l'exige.
        precise = any((article[key] * 100) % 1 for key in ("qte_vendue", "qte_retournee"))
        articles_rows.append({"rang": index, **article, "qte_decimales": 3 if precise else 2})

    debuts = [period.debut_affiche for period in periods if period.debut_affiche]
    multi = len(periods) > 1
    numero = periods[0].numero if (len(periods) == 1 and kind in {KIND_Z, KIND_A}) else None
    total_documents = sum(entry["nombre"] for entry in sections_types)
    total_incompletes = sum(entry["incompletes"] for entry in sections_types)

    contenu = {
        "kind": kind,
        "numero": numero,
        "entreprise": {
            "nom": getattr(config, "nom_entreprise", "") or "",
            "nif": getattr(config, "nif", "") or "",
            "isf": getattr(config, "isf_dgi", "") or "",
        },
        "points": [
            {
                "id": period.point_de_vente.pk,
                "nom": period.point_de_vente.nom,
                "numero": period.numero if kind in {KIND_Z, KIND_A} else None,
                "debut": _display(period.debut_affiche),
                "fin": _display(period.fin),
                "nombre_factures": per_point[period.point_de_vente.pk]["nombre"],
                "montant_total": _money(per_point[period.point_de_vente.pk]["montant"]),
            }
            for period in periods
        ],
        "multi_points": multi,
        "date_rapport": _display(periods[0].fin if kind == KIND_P and periods else generated_at),
        "debut": _display(min(debuts)) if debuts else "",
        "fin": _display(max(period.fin for period in periods)) if periods else _display(generated_at),
        "genere_le": _display(generated_at),
        "genere_par": (user.get_full_name() or user.username) if user is not None else "",
        "types": sections_types,
        "paiements": [{"code": code, "libelle": label, "montant": _money(payments[code])} for code, label in PAYMENT_TYPES],
        "reductions": [
            {"type": code, "montant": _money(values["montant"]), "impot": _money(values["impot"])}
            for code, values in reductions.items()
        ],
        "articles": articles_rows,
        "totaux": {
            "nombre_factures": total_documents,
            "incompletes": total_incompletes,
            "montant_net": _money(sum((entry["montant"] for entry in per_point.values()), ZERO)),
        },
    }
    contenu["titre"] = report_title(contenu)
    return contenu


def report_title(contenu):
    """
    Titre du rapport dans la langue active.

    Le contenu fige ne garde que le type et le numero, pour qu'un rapport
    reimprime s'affiche dans la langue de celui qui le consulte.
    """

    kind = contenu.get("kind")
    if kind == KIND_X:
        return gettext("Rapport X quotidien")
    if kind == KIND_P:
        return gettext("Rapport X périodique")
    numero = contenu.get("numero")
    points = contenu.get("points") or []
    if numero is None and len(points) == 1:
        # Rapports figes avant l'ajout du champ `numero`.
        numero = points[0].get("numero")
    label = gettext("Rapport Z") if kind == KIND_Z else gettext("Rapport A")
    return f"{label} #{numero}" if numero else label


# ---------------------------------------------------------------------------
# Clotures Z / A
# ---------------------------------------------------------------------------

def create_closure_report(points, type_rapport, user):
    """
    Genere un rapport Z ou A, fige son contenu et cloture la session de chaque point de vente.

    Les points de vente sont verrouilles pour que deux clotures simultanees ne
    puissent pas reprendre la meme session ni reutiliser un numero.
    """

    if type_rapport not in {KIND_Z, KIND_A}:
        raise ValueError("Seuls les rapports Z et A remettent les compteurs a zero.")
    if not points:
        raise ValueError("Aucun point de vente a cloturer.")

    with transaction.atomic():
        locked = list(PointDeVente.objects.select_for_update().filter(pk__in=[point.pk for point in points]).order_by("pk"))
        locked.sort(key=lambda point: (point.nom or "").lower())
        fin = timezone.now()
        periods = build_session_periods(locked, type_rapport, fin=fin)
        contenu = compute_report_content(periods, type_rapport, generated_at=fin, user=user)
        debuts = [period.debut for period in periods if period.debut]
        rapport = RapportFiscalDGI.objects.create(
            type_rapport=type_rapport,
            date_debut=min(debuts) if len(debuts) == len(periods) else None,
            date_fin=fin,
            nombre_factures=contenu["totaux"]["nombre_factures"],
            montant_total=contenu["totaux"]["montant_net"],
            contenu=contenu,
            created_by=user if getattr(user, "pk", None) else None,
        )
        ClotureFiscaleDGI.objects.bulk_create(
            [
                ClotureFiscaleDGI(
                    rapport=rapport,
                    type_rapport=type_rapport,
                    point_de_vente=period.point_de_vente,
                    numero=period.numero,
                    date_debut=period.debut,
                    date_fin=fin,
                )
                for period in periods
            ]
        )
    return rapport


def accessible_reports_queryset(user):
    """Rapports Z/A dont tous les points de vente sont dans le perimetre de l'utilisateur."""

    accessible_ids = get_accessible_point_de_vente_queryset(user).values("pk")
    return (
        RapportFiscalDGI.objects.exclude(clotures__point_de_vente__in=PointDeVente.objects.exclude(pk__in=accessible_ids))
        .filter(clotures__isnull=False)
        .distinct()
        .select_related("created_by")
        .prefetch_related("clotures__point_de_vente")
    )
