"""Calcul des achats avec les regles fiscales partagees des factures."""
from decimal import Decimal, ROUND_DOWN, ROUND_HALF_UP

from facturation.fiscal_rules import (
    compute_invoice_tax_totals, compute_line_tax_breakdown,
    compute_specific_tax_amount, get_tax_group_rule,
)

CENT = Decimal("0.01")


def product_tax_input(product, net, quantity):
    group = product.taxgroup
    return {"net": net, "quantity": quantity, "rate": Decimal(str(getattr(group, "tax", 0) or 0)),
        "group": str(getattr(group, "code", "") or "A").strip().upper(),
        "specific_value": str(product.taxe_specifique_valeur or "") if product.est_taxe_specifique else ""}


def allocate_cents(amounts, total):
    """Ventile un total arrondi sans perdre de centime, dans l'ordre des lignes."""
    allocations = [amount.quantize(CENT, rounding=ROUND_DOWN) for amount in amounts]
    remaining = int((total - sum(allocations, Decimal("0"))) / CENT)
    fractions = [amount - base for amount, base in zip(amounts, allocations)]
    order = sorted(range(len(amounts)), key=lambda index: (-fractions[index], index))
    for index in order[:remaining]:
        allocations[index] += CENT
    return allocations


def compute_purchase_invoice(lines, mode, global_discount=Decimal("0")):
    """Prix nets commerciaux, groupes et taxes figes ; remise globale en TTC."""
    lines = list(lines)
    breakdowns = []
    for line in lines:
        specific = compute_specific_tax_amount(line["net"], line["quantity"], line["specific_value"])
        breakdowns.append(compute_line_tax_breakdown(
            subtotal=line["net"], tax_rate=line["rate"], mode_dgi=mode,
            tax_group_code=line["group"], specific_tax_amount=specific,
        ))
    totals = compute_invoice_tax_totals(breakdowns, global_discount)
    if Decimal(str(global_discount or 0)) > totals["ttc_before_discount"]:
        raise ValueError("La remise globale ne peut pas depasser le total TTC des lignes.")
    ratio = totals["discount_ratio"]
    ht = allocate_cents([line["ht_amount"] * ratio for line in breakdowns], totals["total_ht"])
    vat = allocate_cents([line["tax_amount"] * ratio for line in breakdowns], totals["total_tva"])
    gross = totals["ttc_before_discount"]
    discount = Decimal(str(global_discount or 0)).quantize(CENT, rounding=ROUND_HALF_UP)
    discounts = allocate_cents([
        discount * line["ttc_amount"] / gross if gross else Decimal("0") for line in breakdowns
    ], discount)
    computed = []
    for index, breakdown in enumerate(breakdowns):
        specific = (breakdown["specific_tax_amount"] * ratio).quantize(CENT, rounding=ROUND_HALF_UP)
        full_vat = get_tax_group_rule(lines[index]["group"])["vat_mode"] == "full_amount"
        if not full_vat:
            specific = min(specific, ht[index])
        computed.append({"ht": ht[index], "tva": vat[index], "ttc": ht[index] + vat[index],
            "specific": specific, "base_ht": Decimal("0") if full_vat else ht[index] - specific,
            "discount": discounts[index]})
    return {**totals, "lines": computed}
