"""Presentation des montants figes de la facture, sans recalcul du catalogue."""

from decimal import Decimal
from django.utils import timezone
from dgi.tax_groups import get_tax_group_label
from facturation.fiscal_rules import get_tax_group_rule


def build_achat_document_context(achat):
    lignes = list(achat.lignes.all())
    taxes = {}
    for ligne in lignes:
        rate, code = ligne.taux_tva, ligne.groupe_taxation_snapshot
        ligne.vat_mode_affiche = get_tax_group_rule(code)["vat_mode"]
        row = taxes.setdefault((code, rate), {"code": code, "taux": rate,
            "label": ligne.groupe_taxation_libelle_snapshot or get_tax_group_label(code),
            "vat_mode": ligne.vat_mode_affiche,
            "ht": Decimal("0"), "tva": Decimal("0"), "ttc": Decimal("0"), "ts_valeur": Decimal("0")})
        row["ht"] += ligne.montant_base_ht
        row["tva"] += ligne.montant_tva
        row["ttc"] += ligne.montant_ttc
        row["ts_valeur"] += ligne.montant_taxe_specifique
    return {"invoice_lines": lignes, "tax_details": sorted(taxes.values(), key=lambda row: (row["code"], row["taux"])),
        "has_tax_specific": any(line.est_taxe_specifique_snapshot for line in lignes), "printed_at": timezone.now()}
