"""
Services consultatifs des rapports.

Le projet expose deja les routes historiques des rapports via `facturation`.
Ce module centralise uniquement les calculs et contextes d'affichage sans
modifier les flux critiques de vente, fiscalisation ou paiement.
"""

from collections import OrderedDict
from datetime import datetime, time, timedelta
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP

from comptabilite.services import (
    build_chiffre_affaires_payload as isolated_build_chiffre_affaires_payload,
    build_rapport_journalier_context as isolated_build_rapport_journalier_context,
    build_rapport_mensuel_context as isolated_build_rapport_mensuel_context,
    build_rapport_mensuel_point_vente_context as isolated_build_rapport_mensuel_point_vente_context,
    build_rapport_mensuel_taxation_context as isolated_build_rapport_mensuel_taxation_context,
    build_rapport_mensuel_type_facture_context as isolated_build_rapport_mensuel_type_facture_context,
    build_rapport_vendeurs_context as isolated_build_rapport_vendeurs_context,
)
from django.db.models import Count, Sum
from django.utils import timezone

from facturation.fiscal_rules import (
    compute_line_tax_breakdown,
    compute_product_specific_tax_amount,
)
from facturation.models import Commande, Configuration, LigneCommande, Paiement
from dgi.tax_groups import get_tax_group_label


MONEY_STEP = Decimal("0.01")
QTY_STEP = Decimal("0.001")


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 Decimal("0")


def _quantize_money(value):
    """Normalise un montant monetaire sur deux decimales."""

    return _decimal(value).quantize(MONEY_STEP, rounding=ROUND_HALF_UP)


def _quantize_qty(value):
    """Normalise une quantite sur trois decimales pour les rapports."""

    return _decimal(value).quantize(QTY_STEP, rounding=ROUND_HALF_UP)


def _parse_date(raw_value):
    """Analyse une date au format `YYYY-MM-DD` en restant tolerante aux erreurs."""

    if not raw_value:
        return None
    try:
        return datetime.strptime(str(raw_value).strip(), "%Y-%m-%d").date()
    except ValueError:
        return None


def _get_report_filters(date_debut, date_fin, point_de_vente=None):
    """Construit les filtres dates/perimetre reutilises par les rapports."""

    start_dt = timezone.make_aware(datetime.combine(date_debut, time.min))
    end_dt = timezone.make_aware(datetime.combine(date_fin + timedelta(days=1), time.min))
    filters = {
        "date_commande__gte": start_dt,
        "date_commande__lt": end_dt,
    }
    if point_de_vente is not None:
        filters["point_de_vente"] = point_de_vente
    return filters


def _get_config():
    """Retourne la configuration globale utile aux rapports fiscaux."""

    return Configuration.objects.first()


def _channel_label(channel_code):
    """Traduit un code de canal fiscal en libelle lisible pour l'interface."""

    normalized = str(channel_code or "").strip().upper()
    labels = {
        "EMCF": "e-MCF / DGI",
        "MCF": "MCF physique",
        "NON_FISCALISE": "Non fiscalise",
        "NON_RENSEIGNE": "Canal non renseigne",
    }
    return labels.get(normalized, normalized or "Canal non renseigne")


def _fallback_label(config):
    """Traduit le mode de secours fiscal configure en libelle lisible."""

    labels = {
        "ASK_USER": "Demander confirmation",
        "AUTO": "Automatique",
        "DISABLED": "Desactive",
    }
    return labels.get(str(getattr(config, "fiscal_fallback_mode", "") or "").upper(), "")


def _is_fiscalized_document(commande):
    """Indique si une commande semble deja fiscalisee localement."""

    markers = (
        getattr(commande, "codedefdgi", ""),
        getattr(commande, "uid", ""),
        getattr(commande, "qrCode", ""),
        getattr(commande, "nim", ""),
        getattr(commande, "counters", ""),
        getattr(commande, "dateTimedgi", ""),
        getattr(commande, "fiscal_channel", ""),
    )
    return any(str(value or "").strip() for value in markers)


def _resolve_channel_key(commande):
    """Determine le canal fiscal a afficher pour une commande donnee."""

    channel = str(getattr(commande, "fiscal_channel", "") or "").strip().upper()
    if channel:
        return channel
    if _is_fiscalized_document(commande):
        return "NON_RENSEIGNE"
    return "NON_FISCALISE"


def get_rapport_context(request):
    """Extrait et securise la plage de dates demandee dans la requete."""

    today = timezone.localdate()
    date_debut = _parse_date(request.GET.get("date_debut")) or today
    date_fin = _parse_date(request.GET.get("date_fin")) or today
    if date_fin < date_debut:
        date_debut, date_fin = date_fin, date_debut
    return date_debut, date_fin


def _load_report_commandes(date_debut, date_fin, point_de_vente=None):
    """Charge les commandes necessaires aux rapports avec leurs relations utiles."""

    queryset = (
        Commande.objects.filter(**_get_report_filters(date_debut, date_fin, point_de_vente))
        .select_related("client", "point_de_vente")
        .prefetch_related(
            "lignes__produit__taxgroup",
            "paiements__mode_paiement",
        )
        .order_by("date_commande", "numero")
    )
    return list(queryset)


def _build_channel_summary(commandes_by_bucket):
    """Construit une synthese des ventes par canal fiscal et par statut."""

    channel_map = OrderedDict()

    def ensure_channel(channel_key):
        """Initialise la ligne d'agregation d'un canal lorsqu'elle n'existe pas."""

        if channel_key not in channel_map:
            channel_map[channel_key] = {
                "channel": channel_key,
                "label": _channel_label(channel_key),
                "valid_count": 0,
                "cancelled_count": 0,
                "credit_note_count": 0,
                "incomplete_count": 0,
                "total_ttc": Decimal("0"),
            }
        return channel_map[channel_key]

    for bucket_name, commandes in commandes_by_bucket.items():
        for commande in commandes:
            channel_key = _resolve_channel_key(commande)
            entry = ensure_channel(channel_key)
            total = _decimal(getattr(commande, "montant_total", 0))
            if bucket_name == "valid_sales":
                entry["valid_count"] += 1
            elif bucket_name == "cancelled_sales":
                entry["cancelled_count"] += 1
            elif bucket_name == "credit_notes":
                entry["credit_note_count"] += 1
            elif bucket_name == "incomplete_sales":
                entry["incomplete_count"] += 1
            entry["total_ttc"] += total

    result = []
    for channel_key, entry in channel_map.items():
        result.append(
            {
                **entry,
                "total_ttc": _quantize_money(entry["total_ttc"]),
            }
        )
    return result


def _build_tax_details(valid_sales, default_mode_dgi):
    """Construit le detail fiscal agrege a partir des ventes valides."""

    tax_map = OrderedDict()
    total_base_ht = Decimal("0")
    total_specific_tax = Decimal("0")
    total_ht = Decimal("0")
    total_tax = Decimal("0")
    total_ttc = Decimal("0")

    for commande in valid_sales:
        mode_dgi = str(getattr(commande, "mode_dgi", "") or default_mode_dgi or "ttc").strip().lower()
        for ligne in commande.lignes.all():
            produit = ligne.produit
            tax_group = getattr(produit, "taxgroup", None)
            tax_code = str(getattr(tax_group, "code", "") or "SANS").upper()
            tax_rate = _decimal(getattr(tax_group, "tax", 0))
            specific_tax_amount = compute_product_specific_tax_amount(
                produit,
                ligne.sous_total,
                ligne.quantite,
            )
            breakdown = compute_line_tax_breakdown(
                subtotal=ligne.sous_total,
                tax_rate=tax_rate,
                mode_dgi=mode_dgi,
                tax_group_code=tax_code,
                specific_tax_amount=specific_tax_amount,
            )

            if tax_code not in tax_map:
                tax_map[tax_code] = {
                    "code": tax_code,
                    "label": get_tax_group_label(tax_code, getattr(tax_group, "name", "")),
                    "rate": tax_rate,
                    "base_ht": Decimal("0"),
                    "specific_tax": Decimal("0"),
                    "ht": Decimal("0"),
                    "tax": Decimal("0"),
                    "ttc": Decimal("0"),
                }

            entry = tax_map[tax_code]
            entry["base_ht"] += _decimal(breakdown["base_ht_amount"])
            entry["specific_tax"] += _decimal(breakdown["specific_tax_amount"])
            entry["ht"] += _decimal(breakdown["ht_amount"])
            entry["tax"] += _decimal(breakdown["tax_amount"])
            entry["ttc"] += _decimal(breakdown["ttc_amount"])

            total_base_ht += _decimal(breakdown["base_ht_amount"])
            total_specific_tax += _decimal(breakdown["specific_tax_amount"])
            total_ht += _decimal(breakdown["ht_amount"])
            total_tax += _decimal(breakdown["tax_amount"])
            total_ttc += _decimal(breakdown["ttc_amount"])

    tax_details = []
    for entry in tax_map.values():
        tax_details.append(
            {
                "code": entry["code"],
                "label": entry["label"],
                "rate": entry["rate"],
                "base_ht": _quantize_money(entry["base_ht"]),
                "specific_tax": _quantize_money(entry["specific_tax"]),
                "ht": _quantize_money(entry["ht"]),
                "tax": _quantize_money(entry["tax"]),
                "ttc": _quantize_money(entry["ttc"]),
            }
        )

    return {
        "tax_details": tax_details,
        "total_base_ht": _quantize_money(total_base_ht),
        "total_specific_tax": _quantize_money(total_specific_tax),
        "total_ht": _quantize_money(total_ht),
        "total_tax": _quantize_money(total_tax),
        "total_ttc_from_lines": _quantize_money(total_ttc),
    }


def _build_payments(valid_sales):
    """Agrege les paiements des ventes valides par mode de paiement."""

    payment_map = OrderedDict()
    for commande in valid_sales:
        for paiement in commande.paiements.all():
            label = getattr(getattr(paiement, "mode_paiement", None), "designation", None)
            label = label or str(getattr(paiement, "mode_paiement_id", "") or "Mode non renseigne")
            payment_map[label] = payment_map.get(label, Decimal("0")) + _decimal(paiement.montant)

    payments = []
    for label, total in payment_map.items():
        payments.append({"mode_paiement": label, "total": _quantize_money(total)})
    return payments


def _build_fiscal_report_dataset(date_debut, date_fin, point_de_vente=None):
    """Construit le jeu de donnees commun aux rapports fiscaux X, Z et A."""

    config = _get_config()
    commandes = _load_report_commandes(date_debut, date_fin, point_de_vente)

    valid_sales = []
    cancelled_sales = []
    credit_notes = []
    incomplete_sales = []

    for commande in commandes:
        type_facture = str(getattr(commande, "type_facture", "") or "").strip().upper()
        if type_facture in {"FA", "EA"}:
            credit_notes.append(commande)
            continue

        if getattr(commande, "est_annulee", False):
            cancelled_sales.append(commande)
            continue

        if _is_fiscalized_document(commande):
            valid_sales.append(commande)
        else:
            incomplete_sales.append(commande)

    tax_payload = _build_tax_details(valid_sales, getattr(config, "mode_dgi", "ttc"))

    total_ttc = _quantize_money(sum(_decimal(cmd.montant_total) for cmd in valid_sales))
    total_encaisse = _quantize_money(sum(_decimal(cmd.montant_paye) for cmd in valid_sales))
    total_reste = _quantize_money(total_ttc - total_encaisse)
    total_cancelled = _quantize_money(sum(_decimal(cmd.montant_total) for cmd in cancelled_sales))
    total_credit_notes = _quantize_money(sum(_decimal(cmd.montant_total) for cmd in credit_notes))
    total_incomplete = _quantize_money(sum(_decimal(cmd.montant_total) for cmd in incomplete_sales))

    return {
        "config": config,
        "date_debut": date_debut,
        "date_fin": date_fin,
        "generated_at": timezone.now(),
        "point_de_vente": point_de_vente,
        "point_de_vente_label": getattr(point_de_vente, "nom", ""),
        "report_source_label": "Rapport consultatif local",
        "primary_channel_label": _channel_label(getattr(config, "fiscal_primary_channel", "")) if config else "",
        "fallback_mode_label": _fallback_label(config) if config else "",
        "count_valid": len(valid_sales),
        "count_cancelled": len(cancelled_sales),
        "count_credit_notes": len(credit_notes),
        "count_incomplete": len(incomplete_sales),
        "total_ttc": total_ttc,
        "total_encaisse": total_encaisse,
        "total_reste": total_reste,
        "total_cancelled": total_cancelled,
        "total_credit_notes": total_credit_notes,
        "total_incomplete": total_incomplete,
        "payments": _build_payments(valid_sales),
        "channel_details": _build_channel_summary(
            {
                "valid_sales": valid_sales,
                "cancelled_sales": cancelled_sales,
                "credit_notes": credit_notes,
                "incomplete_sales": incomplete_sales,
            }
        ),
        "valid_sales": valid_sales,
        "cancelled_sales": cancelled_sales,
        "credit_notes": credit_notes,
        "incomplete_sales": incomplete_sales,
        **tax_payload,
    }


def build_rapport_journalier_context(request):
    """Prepare le contexte du rapport journalier detaille par produit."""

    date_debut, date_fin = get_rapport_context(request)
    point_de_vente = getattr(request.user, "point_de_vente", None)
    config = _get_config()

    qs_commandes = (
        Commande.objects.filter(**_get_report_filters(date_debut, date_fin, point_de_vente))
        .select_related("client")
        .prefetch_related("lignes__produit")
    )

    total_ht = qs_commandes.aggregate(Sum("montant_total"))["montant_total__sum"] or 0
    total_paye = qs_commandes.aggregate(Sum("montant_paye"))["montant_paye__sum"] or 0

    lignes_all = LigneCommande.objects.filter(commande__in=qs_commandes).select_related("produit")
    produits_headers = {}
    for ligne in lignes_all:
        produits_headers[ligne.produit_id] = str(ligne.produit.nom or "").upper()

    headers_sorted = [
        {"id": product_id, "nom": product_name}
        for product_id, product_name in sorted(produits_headers.items(), key=lambda item: item[1])
    ]

    rapport_lines = []
    totaux_map = {product_id: {"qty": Decimal("0"), "val": Decimal("0")} for product_id in produits_headers.keys()}

    for commande in qs_commandes:
        row = {
            "client": commande.client.nom_complet if commande.client else "Client Passage",
            "date": commande.date_commande,
            "total_general": commande.montant_total,
        }
        cmd_products = {}
        for ligne in commande.lignes.all():
            product_id = ligne.produit_id
            if product_id in produits_headers:
                cmd_products[product_id] = {
                    "qty": ligne.quantite,
                    "pu": ligne.prix_unitaire,
                    "val": ligne.sous_total,
                }
                totaux_map[product_id]["qty"] += _decimal(ligne.quantite)
                totaux_map[product_id]["val"] += _decimal(ligne.sous_total)

        row["products_list"] = [cmd_products.get(header["id"]) for header in headers_sorted]
        rapport_lines.append(row)

    return {
        "date_debut": date_debut,
        "date_fin": date_fin,
        "global_stats": {
            "ca_total": total_ht,
            "encaisse": total_paye,
            "credit": _decimal(total_ht) - _decimal(total_paye),
            "nb_ventes": qs_commandes.count(),
        },
        "product_headers": headers_sorted,
        "rapport_lines": rapport_lines,
        "totaux_row": [totaux_map[header["id"]] for header in headers_sorted],
        "config": config,
    }


def build_rapport_mensuel_context(request):
    """Prepare le contexte du rapport mensuel consolide par jour."""

    today = timezone.localdate()
    raw_year = request.GET.get("year", today.year)
    raw_month = request.GET.get("month", today.month)

    try:
        year = int(raw_year)
    except (TypeError, ValueError):
        year = today.year

    try:
        month = int(raw_month)
    except (TypeError, ValueError):
        month = today.month

    if month < 1 or month > 12:
        month = today.month

    point_de_vente = getattr(request.user, "point_de_vente", None)

    # On utilise une plage datetime explicite comme pour le rapport journalier.
    # Dans ce projet, les lookups __year / __month sur date_commande ne
    # remontent pas toujours correctement les ventes selon le backend/timezone.
    try:
        month_start = datetime(year, month, 1)
    except ValueError:
        year = today.year
        month = today.month
        month_start = datetime(year, month, 1)

    if month == 12:
        next_month_start = datetime(year + 1, 1, 1)
    else:
        next_month_start = datetime(year, month + 1, 1)

    filters = {
        "date_commande__gte": timezone.make_aware(month_start),
        "date_commande__lt": timezone.make_aware(next_month_start),
    }
    if point_de_vente is not None:
        filters["point_de_vente"] = point_de_vente

    qs_month = Commande.objects.filter(**filters).order_by("date_commande")

    # Le regroupement est volontairement fait en Python pour rester fiable
    # meme si le backend SQL ne dispose pas des definitions timezone attendues
    # par les fonctions de troncature datetime.
    ventes_map = OrderedDict()
    for commande in qs_month:
        jour = timezone.localtime(commande.date_commande).date()
        if jour not in ventes_map:
            ventes_map[jour] = {
                "jour": jour,
                "total": Decimal("0"),
                "count": 0,
            }
        ventes_map[jour]["total"] += _decimal(commande.montant_total)
        ventes_map[jour]["count"] += 1

    ventes_par_jour = [
        {
            "jour": jour,
            "total": _quantize_money(data["total"]),
            "count": data["count"],
        }
        for jour, data in ventes_map.items()
    ]

    return {
        "ventes_par_jour": ventes_par_jour,
        "total_mois": qs_month.aggregate(Sum("montant_total"))["montant_total__sum"] or 0,
        "month_label": f"{month}/{year}",
        "current_year": year,
        "current_month": month,
    }


def build_rapport_vendeurs_context(request):
    """Prepare le contexte du rapport de performance par vendeur."""

    today = timezone.localdate()
    default_start = today.replace(day=1)
    date_debut = _parse_date(request.GET.get("date_debut")) or default_start
    date_fin = _parse_date(request.GET.get("date_fin")) or today
    if date_fin < date_debut:
        date_debut, date_fin = date_fin, date_debut

    point_de_vente = getattr(request.user, "point_de_vente", None)
    filters = _get_report_filters(date_debut, date_fin, point_de_vente)
    qs = Commande.objects.filter(**filters)

    performances = (
        qs.values("vendeur__username")
        .annotate(chiffre_affaire=Sum("montant_total"), ventes_count=Count("id"))
        .order_by("-chiffre_affaire")
    )

    return {
        "date_debut": date_debut,
        "date_fin": date_fin,
        "performances": performances,
    }


def build_rapport_a_context(request):
    """Prepare le contexte du rapport A a partir des ventes fiscales valides."""

    date_debut, date_fin = get_rapport_context(request)
    point_de_vente = getattr(request.user, "point_de_vente", None)
    dataset = _build_fiscal_report_dataset(date_debut, date_fin, point_de_vente)

    product_map = OrderedDict()

    # Le rapport A reste periodique et consultatif: on agrege uniquement les
    # ventes fiscales valides deja presentes localement, sans interroger MCF/DGI.
    for commande in dataset["valid_sales"]:
        mode_dgi = str(getattr(commande, "mode_dgi", "") or getattr(dataset["config"], "mode_dgi", "ttc")).strip().lower()
        for ligne in commande.lignes.all():
            produit = ligne.produit
            tax_group = getattr(produit, "taxgroup", None)
            tax_code = str(getattr(tax_group, "code", "") or "SANS").upper()
            tax_rate = _decimal(getattr(tax_group, "tax", 0))
            specific_tax_amount = compute_product_specific_tax_amount(
                produit,
                ligne.sous_total,
                ligne.quantite,
            )
            breakdown = compute_line_tax_breakdown(
                subtotal=ligne.sous_total,
                tax_rate=tax_rate,
                mode_dgi=mode_dgi,
                tax_group_code=tax_code,
                specific_tax_amount=specific_tax_amount,
            )

            if produit.pk not in product_map:
                product_map[produit.pk] = {
                    "produit__code_sku": produit.code_sku,
                    "produit__nom": produit.nom,
                    "produit__taxgroup__tax": tax_rate,
                    "produit__taxgroup__code": tax_code,
                    "produit__taxgroup__label": get_tax_group_label(
                        tax_code,
                        getattr(tax_group, "name", ""),
                    ),
                    "documents": set(),
                    "qte_vendue": Decimal("0"),
                    "base_ht_total": Decimal("0"),
                    "specific_tax_total": Decimal("0"),
                    "total_ht_fiscal": Decimal("0"),
                    "total_tax": Decimal("0"),
                    "ttc_total": Decimal("0"),
                }

            entry = product_map[produit.pk]
            entry["documents"].add(commande.pk)
            entry["qte_vendue"] += _decimal(ligne.quantite)
            entry["base_ht_total"] += _decimal(breakdown["base_ht_amount"])
            entry["specific_tax_total"] += _decimal(breakdown["specific_tax_amount"])
            entry["total_ht_fiscal"] += _decimal(breakdown["ht_amount"])
            entry["total_tax"] += _decimal(breakdown["tax_amount"])
            entry["ttc_total"] += _decimal(breakdown["ttc_amount"])

    lignes = []
    for entry in sorted(product_map.values(), key=lambda item: str(item["produit__nom"]).lower()):
        lignes.append(
            {
                **entry,
                "documents_count": len(entry["documents"]),
                "qte_vendue": _quantize_qty(entry["qte_vendue"]),
                "base_ht_total": _quantize_money(entry["base_ht_total"]),
                "specific_tax_total": _quantize_money(entry["specific_tax_total"]),
                "total_ht_fiscal": _quantize_money(entry["total_ht_fiscal"]),
                "total_tax": _quantize_money(entry["total_tax"]),
                "ttc_total": _quantize_money(entry["ttc_total"]),
                # Compatibilite avec l'ancien template.
                "total_vente": _quantize_money(entry["ttc_total"]),
            }
        )

    dataset.update(
        {
            "lignes": lignes,
            "total_qte_vendue": _quantize_qty(sum((line["qte_vendue"] for line in lignes), Decimal("0"))),
            "total_documents": dataset["count_valid"],
            "total_ttc": _quantize_money(sum((line["ttc_total"] for line in lignes), Decimal("0"))),
        }
    )
    return dataset


def get_xz_data_logic(date_debut, date_fin, point_de_vente=None):
    """Expose le jeu de donnees commun reutilise par les rapports X et Z."""

    return _build_fiscal_report_dataset(date_debut, date_fin, point_de_vente)


def build_chiffre_affaires_payload():
    """Retourne un resume simple du chiffre d'affaires pour l'API rapports."""

    total_ventes = Commande.objects.aggregate(Sum("montant_total"))["montant_total__sum"] or 0
    total_encaisse = Commande.objects.aggregate(Sum("montant_paye"))["montant_paye__sum"] or 0
    return {
        "chiffre_affaires_total": total_ventes,
        "total_encaisse": total_encaisse,
        "creances": _decimal(total_ventes) - _decimal(total_encaisse),
    }


# On re-exporte la couche de comptabilite simple depuis rapports pour conserver
# les imports historiques sans changer les points d'entree publics existants.
build_rapport_journalier_context = isolated_build_rapport_journalier_context
build_rapport_mensuel_context = isolated_build_rapport_mensuel_context
build_rapport_mensuel_taxation_context = isolated_build_rapport_mensuel_taxation_context
build_rapport_mensuel_point_vente_context = isolated_build_rapport_mensuel_point_vente_context
build_rapport_mensuel_type_facture_context = isolated_build_rapport_mensuel_type_facture_context
build_rapport_vendeurs_context = isolated_build_rapport_vendeurs_context
build_chiffre_affaires_payload = isolated_build_chiffre_affaires_payload
