"""Filtres de la liste Pro-Forma : memes regles que l'historique des factures.

Point de vente, statut, periode et recherche (numero de pro-forma, client ou
montant) sont partages par la liste et ses exports Excel / PDF.
"""

import re

from django.db.models import CharField, Q, Value
from django.db.models.functions import Cast, Replace

from facturation.access_control import get_accessible_point_de_vente_queryset
from facturation.views import (
    _can_select_all_commande_points,
    _commande_history_datetime_bound,
    _is_commande_amount_search_term,
    _normalize_commande_amount_search,
    _normalize_commande_number_search,
    _parse_commande_history_date,
    _parse_exact_commande_amount_search,
)

from .models import Proforma

PROFORMA_POINT_FILTER_PARAM = "pdv"
PROFORMA_STATUS_FILTER_PARAM = "statut"
PROFORMA_CLIENT_FILTER_PARAM = "client"
PROFORMA_START_DATE_FILTER_PARAM = "date_debut"
PROFORMA_END_DATE_FILTER_PARAM = "date_fin"
PROFORMA_SEARCH_FILTER_PARAM = "q"


def resolve_proforma_filters(user, query_params):
    """Valide les filtres saisis sans jamais elargir le perimetre de l'utilisateur."""

    accessible_points = get_accessible_point_de_vente_queryset(user).order_by("nom")
    raw_point_id = str(query_params.get(PROFORMA_POINT_FILTER_PARAM) or "").strip()
    raw_status = str(query_params.get(PROFORMA_STATUS_FILTER_PARAM) or "").strip().upper()
    raw_client_id = str(query_params.get(PROFORMA_CLIENT_FILTER_PARAM) or "").strip()
    errors = []
    selected_point_id = None
    selected_client_id = None

    # Vide ou « all » : tout le perimetre deja limite par proformas_accessibles.
    if raw_point_id and raw_point_id != "all":
        try:
            requested_point_id = int(raw_point_id)
        except ValueError:
            errors.append("Filtre point de vente invalide.")
        else:
            if accessible_points.filter(pk=requested_point_id).exists():
                selected_point_id = requested_point_id
            else:
                errors.append("Ce point de vente n'est pas autorise pour votre compte.")

    selected_status = ""
    if raw_status:
        if raw_status in dict(Proforma.STATUT_PAIEMENT):
            selected_status = raw_status
        else:
            errors.append("Filtre statut invalide.")

    if raw_client_id:
        if raw_client_id.isdigit():
            selected_client_id = int(raw_client_id)
        else:
            errors.append("Filtre client invalide.")

    selected_start_date, start_date_error = _parse_commande_history_date(
        query_params.get(PROFORMA_START_DATE_FILTER_PARAM), "date de debut"
    )
    selected_end_date, end_date_error = _parse_commande_history_date(
        query_params.get(PROFORMA_END_DATE_FILTER_PARAM), "date de fin"
    )
    errors.extend(error for error in (start_date_error, end_date_error) if error)
    if selected_start_date and selected_end_date and selected_start_date > selected_end_date:
        errors.append("La date de debut doit etre anterieure ou egale a la date de fin.")

    return {
        "accessible_points": accessible_points,
        "can_select_all_points": _can_select_all_commande_points(user),
        "selected_point_id": selected_point_id,
        "selected_status": selected_status,
        "selected_client_id": selected_client_id,
        "selected_start_date": selected_start_date,
        "selected_end_date": selected_end_date,
        "date_start": _commande_history_datetime_bound(selected_start_date),
        "date_end": _commande_history_datetime_bound(selected_end_date, include_day=True),
        "search_query": str(query_params.get(PROFORMA_SEARCH_FILTER_PARAM) or "").strip()[:100],
        "errors": errors,
    }


def apply_proforma_filters(queryset, filters_context):
    """Applique point de vente, statut, client, periode et recherche partielle."""

    if filters_context["errors"]:
        return queryset.none()
    if filters_context["selected_point_id"]:
        queryset = queryset.filter(point_de_vente_id=filters_context["selected_point_id"])
    if filters_context["selected_status"]:
        queryset = queryset.filter(statut_paiement=filters_context["selected_status"])
    if filters_context["selected_client_id"]:
        queryset = queryset.filter(client_id=filters_context["selected_client_id"])
    if filters_context["date_start"]:
        queryset = queryset.filter(date_proforma__gte=filters_context["date_start"])
    if filters_context["date_end"]:
        queryset = queryset.filter(date_proforma__lt=filters_context["date_end"])

    search_query = filters_context["search_query"]
    search_terms = [
        term for term in re.split(r"\s+", search_query) if term and term.casefold() not in {"fc", "cdf"}
    ][:8]
    if not search_terms:
        return queryset

    queryset = queryset.annotate(
        proforma_search_total=Cast("montant_total", output_field=CharField()),
        proforma_search_numero_compact=Replace("numero", Value("-"), Value("")),
    )
    # Comme les factures : chaque mot doit correspondre au numero (PF-2026-00032
    # ou PF202600032), au client ou au montant.
    search_filter = Q()
    for term in search_terms:
        term_filter = Q(numero__icontains=term) | Q(client__nom_complet__icontains=term)
        normalized_number = _normalize_commande_number_search(term)
        if normalized_number:
            term_filter |= Q(proforma_search_numero_compact__icontains=normalized_number)
        normalized_amount = _normalize_commande_amount_search(term)
        if normalized_amount and _is_commande_amount_search_term(term):
            term_filter |= Q(proforma_search_total__icontains=normalized_amount)
        search_filter &= term_filter
    exact_amount = _parse_exact_commande_amount_search(search_query)
    if exact_amount is not None:
        search_filter |= Q(montant_total=exact_amount)
    return queryset.filter(search_filter)
