"""
Services de presentation relies aux ecrans client.

Le modele et sa consommation metier restent dans facturation ; seuls les
helpers de consultation sont centralises ici.
"""

import re

from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Sum

from facturation.models import Client, Commande


def get_client_list_queryset():
    """Retourne la liste client avec les jointures utiles a l'affichage."""
    return Client.objects.select_related("client_type").all()


def get_client_detail_queryset():
    """Retourne le queryset detail sans modifier le comportement fonctionnel."""
    return Client.objects.select_related("client_type").all()


def build_client_detail_context(client):
    """Construit le contexte historique et statistique de la fiche client."""
    commandes = Commande.objects.filter(client=client).order_by("-date_commande")
    total_achats = commandes.aggregate(Sum("montant_total"))["montant_total__sum"] or 0
    total_paye = commandes.aggregate(Sum("montant_paye"))["montant_paye__sum"] or 0

    return {
        "commandes": commandes,
        "total_achats": total_achats,
        "total_paye": total_paye,
        "reste_a_payer": total_achats - total_paye,
    }


def get_client_blocking_relations(client):
    """
    Recense les relations reverse deja liees a un client.

    Cette verification permet de bloquer les suppressions qui casseraient
    l'historique des ventes, des avoirs, des proformas ou d'autres donnees
    metier deja rattachees au client.
    """

    blocking_relations = []
    seen_labels = set()

    for relation in client._meta.related_objects:
        accessor_name = relation.get_accessor_name()
        if not accessor_name:
            continue

        try:
            accessor = getattr(client, accessor_name)
        except ObjectDoesNotExist:
            continue

        if hasattr(accessor, "all"):
            has_related_records = accessor.all().exists()
        else:
            has_related_records = accessor is not None

        if not has_related_records:
            continue

        relation_label = str(
            relation.related_model._meta.verbose_name_plural
            or relation.related_model._meta.verbose_name
            or relation.related_model.__name__
        )

        if relation_label in seen_labels:
            continue

        seen_labels.add(relation_label)
        blocking_relations.append(
            {
                "accessor_name": accessor_name,
                "label": relation_label,
                "model": relation.related_model,
            }
        )

    return blocking_relations


def normalize_client_text(value):
    """Normalise un texte libre en ignorant la casse et les espaces superflus."""

    value = str(value or "").strip()
    value = re.sub(r"\s+", " ", value)
    return value.casefold()


def normalize_client_identifier(value):
    """Normalise un identifiant type NIF en supprimant les espaces parasites."""

    value = str(value or "").strip()
    value = re.sub(r"\s+", "", value)
    return value.upper()


def normalize_client_phone(value):
    """Normalise un numero de telephone en supprimant les espaces inutiles."""

    value = str(value or "").strip()
    return re.sub(r"\s+", "", value)


def normalize_client_email(value):
    """Normalise une adresse e-mail en ignorant la casse et les espaces externes."""

    return str(value or "").strip().casefold()


def analyze_client_duplicate_candidates(
    *,
    instance=None,
    nom_complet="",
    telephone="",
    email="",
    nif="",
):
    """
    Analyse les differents types de conflits possibles pour un client.

    Regles appliquees :
    - conflit strict sur le NIF si renseigne ;
    - conflit strict sur le telephone si renseigne ;
    - conflit strict sur nom + telephone ;
    - conflit strict sur nom + e-mail ;
    - signalement simple si seul le nom normalise correspond.
    """

    normalized_name = normalize_client_text(nom_complet)
    normalized_phone = normalize_client_phone(telephone)
    normalized_email = normalize_client_email(email)
    normalized_nif = normalize_client_identifier(nif)

    queryset = Client.objects.all()
    if getattr(instance, "pk", None):
        queryset = queryset.exclude(pk=instance.pk)

    strict_nif_match = None
    strict_phone_match = None
    strict_name_phone_match = None
    strict_name_email_match = None
    similar_name_matches = []
    similar_name_ids = set()

    for client in queryset:
        client_nif = normalize_client_identifier(getattr(client, "nif", ""))
        client_name = normalize_client_text(
            getattr(client, "nom_complet", None) or getattr(client, "name", "")
        )
        client_phone = normalize_client_phone(getattr(client, "telephone", ""))
        client_email = normalize_client_email(getattr(client, "email", ""))

        same_name = bool(normalized_name and client_name and normalized_name == client_name)
        same_phone = bool(normalized_phone and client_phone and normalized_phone == client_phone)
        same_email = bool(normalized_email and client_email and normalized_email == client_email)

        if normalized_nif and client_nif and normalized_nif == client_nif:
            strict_nif_match = strict_nif_match or client

        if same_name and same_phone:
            strict_name_phone_match = strict_name_phone_match or client
        elif same_name and same_email:
            strict_name_email_match = strict_name_email_match or client
        elif same_name and client.pk not in similar_name_ids:
            similar_name_matches.append(client)
            similar_name_ids.add(client.pk)

        if same_phone:
            strict_phone_match = strict_phone_match or client

    return {
        "strict_nif_match": strict_nif_match,
        "strict_phone_match": strict_phone_match,
        "strict_name_phone_match": strict_name_phone_match,
        "strict_name_email_match": strict_name_email_match,
        "similar_name_matches": similar_name_matches,
    }
