"""
Tests de coherence FacControl / DGI (specifications v2).

Les montants de reference sont des factures reelles verifiees sur la plateforme
de verification de la DGI (sygdef) : FV-2026-23096, FV-2026-03321 et
FA-2026-00034.
"""

from decimal import Decimal
from unittest.mock import patch

from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase
from django.utils import timezone

from comptabilite.services import _commande_amounts
from dgi.models import ItemType, TaxGroup

from .accounting import accounting_sign, with_accounting_effect
from .fiscal_amounts import compute_device_amounts, distribute_global_discount, parse_fiscal_datetime
from .fiscal_cancellation import FiscalCancellationService
from .fiscal_orchestrator import apply_fiscal_amounts
from .fiscal_preparation import FiscalPayloadBuilder
from .models import Commande, Configuration, LigneCommande, PointDeVente, Produit
from .views import _modifier_effective_lines


RATES = {"A": Decimal("0"), "B": Decimal("16"), "O": Decimal("1")}


class DeviceAmountsTests(SimpleTestCase):
    def test_fv_2026_03321_matches_the_dgi_record(self):
        # 10 lignes groupe B (280 272,00 HT) et 1 ligne groupe O (4 176,00 HT).
        lines = [{"code": "B", "line_total": Decimal("280272.00")}, {"code": "O", "line_total": Decimal("4176.00")}]

        amounts = compute_device_amounts(lines, "ht", RATES)

        self.assertEqual(amounts["total"], Decimal("329333.28"))
        self.assertEqual(amounts["tva"], Decimal("44885.28"))
        self.assertEqual(amounts["groups"]["O"]["tva"], "41.76")

    def test_fa_2026_00034_matches_the_dgi_record(self):
        amounts = compute_device_amounts([{"code": "B", "line_total": Decimal("2064.00")}], "ht", RATES)

        self.assertEqual((amounts["total"], amounts["tva"]), (Decimal("2394.24"), Decimal("330.24")))

    def test_global_discount_is_spread_so_the_device_total_equals_the_invoice(self):
        # FV-2026-23096 : 2 x 2 088 HT (B), remise globale 44,16 -> 4 800,00 TTC.
        amounts = compute_device_amounts(
            [{"code": "B", "line_total": Decimal("4176.00")}], "ht", RATES, global_discount=Decimal("44.16")
        )

        self.assertEqual(amounts["total"], Decimal("4800.00"))
        self.assertEqual(amounts["tva"], Decimal("662.07"))

    def test_discount_allocation_keeps_every_cent(self):
        discounts = distribute_global_discount(
            [Decimal("1000.00"), Decimal("333.33"), Decimal("10.00")],
            [Decimal("1160.00"), Decimal("386.66"), Decimal("11.60")],
            Decimal("100.00"),
        )
        self.assertEqual(sum(discounts), (Decimal("1343.33") - (Decimal("1343.33") * (Decimal("1458.26") / Decimal("1558.26"))).quantize(Decimal("0.01"))))
        self.assertTrue(all(discount >= 0 for discount in discounts))

    def test_fiscal_datetimes_of_emcf_and_mcf_are_read(self):
        self.assertEqual(parse_fiscal_datetime("18/11/2026 18:39:17").strftime("%Y-%m-%d %H:%M:%S"), "2026-11-18 18:39:17")
        self.assertEqual(parse_fiscal_datetime("20250301122547").strftime("%Y-%m-%d %H:%M:%S"), "2025-03-01 12:25:47")
        self.assertIsNone(parse_fiscal_datetime(""))


class FiscalV2DatabaseTests(TestCase):
    def setUp(self):
        self.pdv = PointDeVente.objects.create(nom="PDV V2")
        self.user = get_user_model().objects.create_user(username="caisse_v2", email="caisse_v2@test.com", password="x", point_de_vente=self.pdv)
        self.group_b, _ = TaxGroup.objects.update_or_create(code="B", defaults={"name": "GROUPE B", "tax": Decimal("16.00")})
        item_type = ItemType.objects.create(code="BIE", name="Bien")
        self.product = Produit.objects.create(
            nom="LAM DE SCIE", code_sku="LAM-01", prix_vente=Decimal("2088"), taxgroup=self.group_b, typeart=item_type, actif=True
        )
        Configuration.objects.create(
            taux_change=Decimal("2300"), fiscal_primary_channel="EMCF", fiscal_fallback_mode="DISABLED",
            require_security_before_save=True, nif="A2560363Q", isf_dgi="GBM-GCE-01", mode_dgi="ht", type_dgi="FV",
        )

    def _invoice(self, quantity="2", remise_globale="0", codedefdgi="TEST-FACT-AAAA-BBBB-CCCC-DDDD", total="4844.16", tva="668.16"):
        commande = Commande.objects.create(
            point_de_vente=self.pdv, vendeur=self.user, montant_total=Decimal(total), montant_paye=Decimal(total),
            tva_montant=Decimal(tva), remise_globale=Decimal(remise_globale), taux_change_applique=Decimal("2300"),
            type_facture="FV", mode_dgi="ht", codedefdgi=codedefdgi, fiscal_channel="EMCF",
        )
        LigneCommande.objects.create(
            commande=commande, produit=self.product, quantite=Decimal(quantity), prix_unitaire=Decimal("2088.00"),
            remise=Decimal("0"), sous_total=Decimal("2088.00") * Decimal(quantity), groupe_taxation_snapshot="B",
        )
        return commande

    def test_global_discount_is_sent_on_the_items(self):
        commande = self._invoice(remise_globale="44.16", codedefdgi="", total="4800.00", tva="662.07")

        payload = FiscalPayloadBuilder().build(commande)

        item = payload["items"][0]
        self.assertEqual(item["line_total"], Decimal("4137.93"))
        self.assertEqual(item["original_price"], Decimal("2088.00"))
        self.assertIn("Remise", item["price_modification"])
        amounts = compute_device_amounts([{"code": "B", "line_total": item["line_total"]}], "ht", RATES)
        self.assertEqual((amounts["total"], amounts["tva"]), (Decimal("4800.00"), Decimal("662.07")))

    def test_device_amounts_are_recorded_and_cent_gaps_aligned(self):
        commande = self._invoice(total="4800.00", tva="662.07")
        fields = apply_fiscal_amounts(
            commande,
            {"source": "EMCF", "total": "4800.01", "tva": "662.07", "groups": {}},
            "24/11/2026 23:59:59",
            item_count=1,
        )

        self.assertIn("date_fiscale", fields)
        self.assertEqual(commande.fiscal_total_ttc, Decimal("4800.01"))
        self.assertEqual(commande.montant_total, Decimal("4800.01"))
        # Facture soldee avant l'alignement : elle reste soldee (pas de reste de 0,01).
        self.assertEqual(commande.montant_paye, Decimal("4800.01"))
        self.assertEqual(commande.statut_paiement, "PAYEE")
        self.assertEqual(timezone.localtime(commande.date_fiscale).strftime("%d/%m/%Y %H:%M"), "24/11/2026 23:59")

    def test_reports_use_the_amounts_recorded_by_the_dgi(self):
        commande = self._invoice(total="4800.00", tva="662.07")
        commande.fiscal_total_ttc = Decimal("4844.16")
        commande.fiscal_total_tva = Decimal("668.16")

        self.assertEqual(_commande_amounts(commande), (Decimal("4176.00"), Decimal("668.16"), Decimal("4844.16")))

    def test_every_credit_note_counts_negative(self):
        source = self._invoice()
        credit_note = Commande.objects.create(
            point_de_vente=self.pdv, vendeur=self.user, montant_total=Decimal("2422.08"), tva_montant=Decimal("334.08"),
            type_facture="FA", facture_origine=source, nature_avoir="COR", codedefdgi="TEST-FACT-EEEE-FFFF-GGGG-HHHH",
            mode_dgi="ht",
        )

        signs = dict(with_accounting_effect(Commande.objects.all()).values_list("pk", "accounting_sign"))
        self.assertEqual(signs[source.pk], Decimal("1"))
        self.assertEqual(signs[credit_note.pk], Decimal("-1"))
        self.assertEqual(accounting_sign(credit_note), Decimal("-1"))

    @patch("dgi.emcf_adapter.journal")
    @patch("dgi.emcf_adapter.EdefClient")
    def test_partial_credit_notes_leave_the_source_invoice_untouched(self, client_class, _journal):
        source = self._invoice(quantity="3", total="7266.24", tva="1002.24")
        client = client_class.return_value
        client.info_status.return_value = {"status": True, "nif": "A2560363Q"}
        client.create_invoice.return_value = {"uid": "uid-fa", "total": 2422.08, "vtotal": 334.08}
        client.confirm_invoice.side_effect = [
            {"dateTime": "24/11/2026 10:00:00", "codeDEFDGI": f"TEST-FACT-AVR{i}-BBBB-CCCC-DDDD", "counters": f"{i}/9 FA",
             "nim": "CD01004241-1", "qrCode": "QR"}
            for i in (1, 2, 3)
        ]
        line = {"produit": self.product, "quantite": Decimal("1"), "prix_unitaire": Decimal("2088.00"),
                "remise": Decimal("0"), "sous_total": Decimal("2088.00"), "groupe_taxation": "B"}

        service = FiscalCancellationService()
        service.cancel_commande(source, "COR", self.user, lignes_a_annuler=[dict(line)])
        source.refresh_from_db()
        service.cancel_commande(source, "RAM", self.user, lignes_a_annuler=[dict(line)])
        source.refresh_from_db()

        # La facture normalisee reste celle de la DGI : 3 articles, 7 266,24.
        self.assertEqual(source.montant_total, Decimal("7266.24"))
        self.assertEqual(source.lignes.get().quantite, Decimal("3.000"))
        self.assertFalse(source.est_annulee)
        credit_notes = Commande.objects.filter(facture_origine=source).order_by("pk")
        self.assertEqual([fa.montant_total for fa in credit_notes], [Decimal("2422.08"), Decimal("2422.08")])
        self.assertEqual(credit_notes[0].fiscal_total_ttc, Decimal("2422.08"))
        # Le reliquat (1 article) reste modifiable / remboursable.
        self.assertEqual([ligne.quantite for ligne in _modifier_effective_lines(source)], [Decimal("1.000")])

        # Le dernier avoir couvre le reliquat et annule la facture de vente.
        service.cancel_commande(source, "RAN", self.user)
        source.refresh_from_db()
        self.assertTrue(source.est_annulee)
        self.assertEqual(Commande.objects.filter(facture_origine=source).count(), 3)
