"""
Regles de calcul fiscal partagees.

Ce fichier centralise les calculs reutilises pour la TVA, les taxes
specifiques et les ventilations necessaires aux ecrans et a la fiscalisation.
"""



from decimal import Decimal, ROUND_HALF_UP

from django.utils.translation import gettext as _


MCF_TAX_GROUP_RULES = {
    "L": {
        "preferred_item_type": "TAX",
        "vat_mode": "none",
    },
    "N": {
        "preferred_item_type": "TAX",
        "vat_mode": "full_amount",
    },
}


def normalize_tax_group_code(value) -> str:
    """Normalise tax group code."""

    return str(value or "").strip().upper()


def normalize_item_type_code(value) -> str:
    """Normalise item type code."""

    code = str(value or "").strip().upper()
    aliases = {
        "BIE": "BIE",
        "BIEN": "BIE",
        "GOOD": "BIE",
        "GOODS": "BIE",
        "SER": "SER",
        "SERVICE": "SER",
        "SERVICES": "SER",
        "TAX": "TAX",
        "TAXE": "TAX",
    }
    return aliases.get(code, code or "BIE")


def resolve_dgi_item_type_code(value) -> str:
    """Retourne un type article accepté par les canaux fiscaux.

    Les anciennes fiches produit peuvent ne pas avoir de relation ``typeart``.
    Le projet traitait déjà ce cas comme un bien dans les adaptateurs MCF et
    dans l'ancien service DGI. Cette fonction rend cette compatibilité unique
    et explicite sans modifier la fiche produit en base.
    """

    normalized = normalize_item_type_code(value)
    return normalized if normalized in {"BIE", "SER", "TAX"} else "BIE"


def missing_tax_group_message(product_name) -> str:
    """Message métier partagé lorsqu'un produit n'est pas fiscalement classé."""

    return _(
        "Le produit « %(product)s » ne possède pas de groupe de taxation valide. "
        "Veuillez configurer son groupe de taxation avant de le facturer."
    ) % {"product": product_name or "ARTICLE"}


def get_tax_group_rule(tax_group_code) -> dict:
    """Recupere tax group rule."""

    code = normalize_tax_group_code(tax_group_code)
    rule = {
        "preferred_item_type": None,
        "vat_mode": "rate",
    }
    rule.update(MCF_TAX_GROUP_RULES.get(code, {}))
    rule["tax_group"] = code
    return rule


def build_mcf_item_type_candidates(base_item_type, tax_group_code) -> list:
    """Construit mcf item type candidates."""

    normalized_base_type = normalize_item_type_code(base_item_type)
    rule = get_tax_group_rule(tax_group_code)
    candidates = []

    for candidate in (rule.get("preferred_item_type"), normalized_base_type):
        normalized_candidate = normalize_item_type_code(candidate)
        if normalized_candidate and normalized_candidate not in candidates:
            candidates.append(normalized_candidate)

    return candidates or [normalized_base_type]


def normalize_mcf_tax_rate(tax_group_code, tax_rate) -> Decimal:
    """Normalise le taux transmis au MCF pour les groupes speciaux."""

    rule = get_tax_group_rule(tax_group_code)
    normalized_rate = Decimal(str(tax_rate or 0))

    # Pour les groupes speciaux MCF (ex. N/L), le boitier attend un
    # traitement pilote par le groupe/type et non un taux "100.00%".
    # On stabilise donc le taux envoye a 0.00 tout en conservant le
    # calcul metier cote SFE via les regles fiscales existantes.
    if rule["vat_mode"] != "rate":
        return Decimal("0.00")

    return normalized_rate


def compute_specific_tax_amount(subtotal, quantity, specific_tax_value) -> Decimal:
    """
    Calcule la taxe specifique deja portee par le produit sans toucher
    au schema de donnees existant.
    """
    raw_value = str(specific_tax_value or "").strip()
    if not raw_value:
        return Decimal("0")

    line_total = Decimal(str(subtotal or 0))
    qty = Decimal(str(quantity or 0))
    if qty <= 0:
        return Decimal("0")

    try:
        if raw_value.endswith("%"):
            return line_total * (Decimal(raw_value[:-1].strip()) / Decimal("100"))
        return Decimal(raw_value) * qty
    except Exception:
        return Decimal("0")


def compute_product_specific_tax_amount(produit, subtotal, quantity) -> Decimal:
    """Calcule product specific tax amount."""

    if not getattr(produit, "est_taxe_specifique", False):
        return Decimal("0")
    return compute_specific_tax_amount(
        subtotal=subtotal,
        quantity=quantity,
        specific_tax_value=getattr(produit, "taxe_specifique_valeur", None),
    )


def compute_line_tax_breakdown(
    subtotal,
    tax_rate,
    mode_dgi,
    tax_group_code=None,
    specific_tax_amount=Decimal("0"),
) -> dict:
    """Calcule line tax breakdown."""

    line_total = Decimal(str(subtotal or 0))
    rate = Decimal(str(tax_rate or 0))
    specific_tax = Decimal(str(specific_tax_amount or 0))
    price_mode = str(mode_dgi or "ttc").strip().lower()
    rule = get_tax_group_rule(tax_group_code)

    if rule["vat_mode"] == "full_amount":
        return {
            "base_ht_amount": Decimal("0"),
            "specific_tax_amount": specific_tax,
            "ht_amount": Decimal("0"),
            "tax_amount": line_total + specific_tax,
            "ttc_amount": line_total + specific_tax,
        }

    if rule["vat_mode"] == "none" or rate <= 0:
        return {
            "base_ht_amount": line_total,
            "specific_tax_amount": specific_tax,
            "ht_amount": line_total + specific_tax,
            "tax_amount": Decimal("0"),
            "ttc_amount": line_total + specific_tax,
        }

    if price_mode == "ttc":
        commercial_tax_amount = line_total - (line_total / (Decimal("1") + (rate / Decimal("100"))))
        base_ht_amount = line_total - commercial_tax_amount
        specific_tax_vat_amount = (specific_tax * rate) / Decimal("100")
        ht_amount = base_ht_amount + specific_tax
        tax_amount = commercial_tax_amount + specific_tax_vat_amount
        ttc_amount = line_total + specific_tax + specific_tax_vat_amount
    else:
        base_ht_amount = line_total
        ht_amount = line_total + specific_tax
        tax_amount = (ht_amount * rate) / Decimal("100")
        ttc_amount = ht_amount + tax_amount

    return {
        "base_ht_amount": base_ht_amount,
        "specific_tax_amount": specific_tax,
        "ht_amount": ht_amount,
        "tax_amount": tax_amount,
        "ttc_amount": ttc_amount,
    }


def compute_invoice_tax_totals(breakdowns, global_discount=Decimal("0")):
    """Totaux de facture : remise TTC et TVA proportionnelle, arrondies au centime."""
    breakdowns = list(breakdowns)
    ht = sum((line["ht_amount"] for line in breakdowns), Decimal("0"))
    vat = sum((line["tax_amount"] for line in breakdowns), Decimal("0"))
    gross = ht + vat
    net = max(Decimal("0"), gross - Decimal(str(global_discount or 0)))
    ratio = net / gross if gross > 0 else Decimal("0")
    ttc = net.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    vat = (vat * ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return {"total_ht": ttc - vat, "total_tva": vat, "total_ttc": ttc,
            "ttc_before_discount": gross, "discount_ratio": ratio}
