"""
Services de lecture pour le tableau de bord.

Cette couche regroupe uniquement des calculs et agregations d'affichage
afin de ne pas toucher au flux critique facture -> fiscalisation -> paiement.
"""

from datetime import datetime, time, timedelta
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP

from django.db.models import Sum
from django.utils import timezone

from facturation.fiscal_rules import compute_product_specific_tax_amount
from facturation.accounting import (
    ACCOUNTING_SIGN_ALIAS,
    FISCAL_TTC_ALIAS,
    FISCAL_TVA_ALIAS,
    accounting_amount_expression,
    revenue_documents,
    revenue_period,
    accounting_sign,
    with_accounting_effect,
)
from facturation.models import Client, Commande, Configuration, LigneCommande
from facturation.serializers import CommandeSerializer, ConfigurationSerializer


def build_dashboard_context():
    """Construit le contexte complet utilise par le dashboard web."""
    context = {}

    today = timezone.localdate()
    day_start = timezone.make_aware(datetime.combine(today, time.min))
    day_end = day_start + timedelta(days=1)
    ventes_aujourdhui_qs = Commande.objects.filter(
        type_facture="FV",
        est_annulee=False,
        date_commande__gte=day_start,
        date_commande__lt=day_end,
    )
    # Meme regle que les rapports : ventes moins avoirs, date et montants DGI.
    accounting_all_qs = revenue_documents(Commande.objects.all())
    accounting_today_qs = revenue_period(accounting_all_qs, day_start, day_end)

    context["ventes_aujourdhui_count"] = ventes_aujourdhui_qs.count()
    context["chiffre_affaires_aujourdhui"] = (
        accounting_today_qs.aggregate(total=Sum(accounting_amount_expression(FISCAL_TTC_ALIAS)))["total"] or 0
    )
    context["ca_global"] = (
        accounting_all_qs.aggregate(total=Sum(accounting_amount_expression(FISCAL_TTC_ALIAS)))["total"] or 0
    )
    context["clients_count"] = Client.objects.count()

    context["ca_global_usd"] = None
    context["dashboard_taux_change"] = None
    config = Configuration.objects.first()
    if config:
        try:
            taux_change = Decimal(str(config.taux_change or 0))
            if taux_change > 0:
                context["dashboard_taux_change"] = taux_change
                context["ca_global_usd"] = (
                    Decimal(str(context["ca_global"] or 0)) / taux_change
                ).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        except (InvalidOperation, TypeError, ValueError, ZeroDivisionError):
            context["ca_global_usd"] = None

    factures_emises_qs = Commande.objects.filter(type_facture="FV", est_annulee=False)
    context["factures_emises_count"] = factures_emises_qs.count()
    context["factures_emises_payees_count"] = factures_emises_qs.filter(
        statut_paiement="PAYEE"
    ).count()
    context["factures_emises_en_attente_count"] = factures_emises_qs.exclude(
        statut_paiement="PAYEE"
    ).count()

    context["ca_global_tva"] = (
        accounting_all_qs.aggregate(total=Sum(accounting_amount_expression(FISCAL_TVA_ALIAS)))["total"] or 0
    )
    context["ca_global_ht"] = (
        Decimal(str(context["ca_global"] or 0))
        - Decimal(str(context["ca_global_tva"] or 0))
    ).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

    montant_factures_emises = (
        factures_emises_qs.aggregate(Sum("montant_total"))["montant_total__sum"] or 0
    )
    if context["factures_emises_count"] > 0:
        context["ticket_moyen"] = (
            Decimal(str(montant_factures_emises))
            / Decimal(str(context["factures_emises_count"]))
        ).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    else:
        context["ticket_moyen"] = Decimal("0.00")

    context["reductions_total"] = (
        factures_emises_qs.aggregate(Sum("remise_globale"))["remise_globale__sum"] or 0
    )
    context["reductions_count"] = factures_emises_qs.filter(remise_globale__gt=0).count()

    context["ticket_moyen_usd"] = None
    context["reductions_total_usd"] = None
    if context["dashboard_taux_change"]:
        context["ticket_moyen_usd"] = (
            Decimal(str(context["ticket_moyen"] or 0))
            / context["dashboard_taux_change"]
        ).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        context["reductions_total_usd"] = (
            Decimal(str(context["reductions_total"] or 0))
            / context["dashboard_taux_change"]
        ).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

    taxes_specifiques_total = Decimal("0.00")
    specific_tax_documents = with_accounting_effect(
        Commande.objects.filter(lignes__produit__est_taxe_specifique=True).distinct()
    ).prefetch_related("lignes__produit")
    for document in specific_tax_documents:
        sign = accounting_sign(document)
        for ligne in document.lignes.all():
            if not ligne.produit.est_taxe_specifique:
                continue
            taxes_specifiques_total += sign * compute_product_specific_tax_amount(
                ligne.produit,
                ligne.sous_total,
                ligne.quantite,
            )
    context["taxes_specifiques_total"] = taxes_specifiques_total.quantize(
        Decimal("0.01"),
        rounding=ROUND_HALF_UP,
    )

    context["dernieres_commandes"] = Commande.objects.all().order_by("-date_commande")[:10]
    return context


def build_dashboard_api_payload(user):
    """Construit la charge utile de l'endpoint API du dashboard."""
    pdv = user.point_de_vente
    config = Configuration.objects.first()
    config_data = ConfigurationSerializer(config).data if config else {}

    recent_sales = Commande.objects.filter(point_de_vente=pdv).order_by("-date_commande")[:5]
    recent_sales_data = CommandeSerializer(recent_sales, many=True).data

    today = timezone.now().date()
    todays_sales = with_accounting_effect(
        Commande.objects.filter(point_de_vente=pdv, date_commande__date=today)
    )
    total_sales_usd = todays_sales.aggregate(
        total=Sum(accounting_amount_expression("montant_total"))
    )["total"] or 0
    total_sales_cdf = float(total_sales_usd) * float(config.taux_change) if config else 0

    user_sales = with_accounting_effect(
        Commande.objects.filter(vendeur=user, date_commande__date=today)
    ).aggregate(total=Sum(accounting_amount_expression("montant_total")))["total"] or 0
    user_sales_cdf = float(user_sales) * float(config.taux_change) if config else 0

    user_info = {
        "username": user.first_name or user.username,
        "pdv_nom": pdv.nom if pdv else "PDV Inconnu",
        "role": user.get_role_display(),
    }

    return {
        "config": config_data,
        "user_info": user_info,
        "stats": {
            "today_usd": total_sales_usd,
            "today_cdf": total_sales_cdf,
            "user_today_usd": user_sales,
            "user_today_cdf": user_sales_cdf,
        },
        "recent_transactions": recent_sales_data,
    }
