"""Parcours Chrome du bouton "Facturer" : Pro-Forma -> POS (rapide puis visuel) -> facture."""

import importlib.util
import os
import re
import tempfile
from decimal import Decimal
from pathlib import Path
from unittest import skipUnless
from unittest.mock import patch

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.cache import cache
from django.urls import reverse

from dgi.models import ItemType, TaxGroup
from facturation.models import (
    Client,
    Commande,
    ConditionnementProduit,
    Configuration,
    ModePaiement,
    PointDeVente,
    Produit,
    ProduitPointVentePrix,
    StockPointDeVente,
)

from .services import ProformaCreationService


@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests Chrome.")
class ProformaInvoiceBrowserTests(StaticLiveServerTestCase):
    FISCAL_RESULT = {"success": True, "channel": "MCF", "commande_id": 1, "fiscal_transaction_id": "pf-browser"}

    def setUp(self):
        cache.clear()
        self.pdv = PointDeVente.objects.create(nom="MAGASIN CENTRAL")
        self.user = get_user_model().objects.create_user(
            username="gedeon", email="gedeon@example.com", role="ADMIN", is_staff=True, point_de_vente=self.pdv,
        )
        Configuration.objects.create(
            nom_entreprise="GBM COMPUTER EXPERT SARL", taux_change=1, type_dgi="FV", mode_dgi="ttc",
            nif="A2560363Q", isf_dgi="GBM-WEB-01",
        )
        group, _ = TaxGroup.objects.update_or_create(code="B", defaults={"name": "Taxable 16%", "tax": 16})
        kind, _ = ItemType.objects.update_or_create(code="BIE", defaults={"name": "Bien"})
        self.product = Produit.objects.create(
            nom="Gum boot 43", code_sku="GUM43", prix_vente=11500, unite_mesure="PAIR", taxgroup=group, typeart=kind,
        )
        self.base_packaging = self.product.conditionnements.get()
        # Le carton par defaut ne doit pas etre repris : la Pro-Forma est chiffree a l'unite.
        ConditionnementProduit.objects.filter(pk=self.base_packaging.pk).update(par_defaut=False)
        ConditionnementProduit.objects.create(
            produit=self.product, code="GUM43-CTN", libelle="Carton", facteur_conversion=12, prix_vente=130000, par_defaut=True,
        )
        self.second = Produit.objects.create(
            nom="Racklet 786", code_sku="RACK786", prix_vente=230000, unite_mesure="U", taxgroup=group, typeart=kind,
        )
        for produit in (self.product, self.second):
            StockPointDeVente.objects.create(produit=produit, point_de_vente=self.pdv, quantite=50)
        self.customer = Client.objects.create(nom_complet="AMBASSADE CANADA", nif="A0585296S", telephone="243835852077")
        ModePaiement.objects.update_or_create(code="ESPECES", defaults={"designation": "Espèces"})
        self.proforma = ProformaCreationService().create_from_payload(self.user, {
            "panier": [{"id": self.product.pk, "qty": 3, "remise": 0}, {"id": self.second.pk, "qty": 1, "remise": 0}],
            "document_mode": "FV",
            "client_id": self.customer.pk,
            "remise_globale": 0,
            "commentaires": ["Livraison au bureau"],
            "paiements": [],
        })
        self.reference = f"Réf Proforma N° {self.proforma.numero}"
        self.client.force_login(self.user)
        self.session_value = self.client.cookies[settings.SESSION_COOKIE_NAME].value
        self.qa_dir = Path(os.environ.get("FACCONTROL_QA_DIR", Path(tempfile.gettempdir()) / "faccontrol-proforma-qa"))
        self.qa_dir.mkdir(parents=True, exist_ok=True)

    def browser(self):
        from contextlib import contextmanager
        from playwright.sync_api import sync_playwright

        @contextmanager
        def session():
            with sync_playwright() as playwright:
                candidates = [os.environ.get("FACCONTROL_CHROME_PATH", ""), r"C:\Program Files\Google\Chrome\Application\chrome.exe"]
                executable = next((value for value in candidates if value and Path(value).is_file()), None)
                browser = playwright.chromium.launch(headless=True, **({"executable_path": executable} if executable else {}))
                context = browser.new_context(viewport={"width": 1440, "height": 900}, locale="fr", service_workers="block")
                context.add_cookies([
                    {"name": settings.SESSION_COOKIE_NAME, "value": self.session_value, "url": self.live_server_url},
                    {"name": settings.LANGUAGE_COOKIE_NAME, "value": "fr", "url": self.live_server_url},
                ])
                page = context.new_page()
                page.add_init_script("window.GScan = Object.assign(window.GScan || {}, {keyboardScanEnabled: false});")
                page.route("**/*", lambda route: route.continue_() if route.request.url.startswith(self.live_server_url) else route.abort())
                errors = []
                page.on("pageerror", lambda error: errors.append(str(error)))
                try:
                    yield page, errors
                finally:
                    context.close()
                    browser.close()
        return session()

    def test_facturer_restores_cart_in_both_modes_and_links_the_invoice(self):
        from playwright.sync_api import expect

        with patch("facturation.views.FiscalOrchestrator.fiscalize_commande", return_value=self.FISCAL_RESULT) as fiscalize:
            with self.browser() as (page, errors):
                page.goto(self.live_server_url + reverse("proforma:list"), wait_until="load")
                page.screenshot(path=str(self.qa_dir / "proforma-list.png"))
                page.get_by_role("link", name="Facturer", exact=True).click()
                page.wait_for_function("window.FacControlQuickBilling && window.FacControlQuickBilling.active")

                # Billing rapide : lignes, client, commentaire et rappel de la Pro-Forma.
                rows = page.locator("#cartTableBody [data-line-key]")
                expect(rows).to_have_count(2)
                expect(rows.first.locator('[data-quick-field="packaging"]')).to_have_value(str(self.base_packaging.pk))
                expect(rows.first.locator('[data-quick-field="quantity"]')).to_have_value("3,000")
                expect(page.locator("#clientSelect")).to_have_value(str(self.customer.pk))
                expect(page.locator(".comment-input").first).to_have_value(self.reference)
                expect(page.locator(".comment-input").nth(1)).to_have_value("Livraison au bureau")
                banner = page.locator("#proformaSourceBanner")
                expect(banner).to_be_visible()
                expect(banner).to_contain_text(self.proforma.numero)
                expect(banner).to_have_class(re.compile(r"\balert-info\b"))
                self.assertNotIn("proforma=", page.url)
                page.screenshot(path=str(self.qa_dir / "proforma-pos-quick.png"))

                # POS visuel : la bascule garde le panier et son rattachement.
                page.locator("#posVisualMode").click()
                expect(page.locator("#pos-app")).to_have_attribute("data-billing-mode", "visual")
                expect(page.locator("#cartTableBody tr")).to_have_count(2)
                expect(page.locator("#productSearchMeta")).to_contain_text("2 / 2")
                expect(banner).to_be_visible()
                expect(page.locator(".payment-amount").first).not_to_have_value("")
                page.screenshot(path=str(self.qa_dir / "proforma-pos-visual.png"))

                page.locator("#btnValidate").click()
                page.wait_for_url(re.compile(r".*/facture/\d+/"))
                self.assertFalse(errors)

        fiscalize.assert_called_once()
        commande = Commande.objects.get()
        self.proforma.refresh_from_db()
        self.assertEqual(self.proforma.facture, commande)
        self.assertEqual(commande.commentaire, f"{self.reference}\nLivraison au bureau")
        self.assertEqual(commande.montant_total, self.proforma.montant_total)
        self.assertEqual(commande.lignes.get(produit=self.product).conditionnement, self.base_packaging)

        with self.browser() as (page, errors):
            page.goto(self.live_server_url + reverse("proforma:detail", args=[self.proforma.pk]), wait_until="load")
            expect(page.get_by_role("link", name=f"Voir la facture {commande.numero}")).to_be_visible()
            expect(page.locator("#printArea")).to_contain_text("FACTURE PRO-FORMA")
            expect(page.locator("#printArea")).not_to_contain_text("ELEMENT SECURITE")
            page.screenshot(path=str(self.qa_dir / "proforma-detail-a4.png"), full_page=True)
            self.assertFalse(errors)

    def test_modifier_reopens_the_proforma_in_the_pos_and_saves_the_same_document(self):
        from playwright.sync_api import expect

        numero = self.proforma.numero
        with self.browser() as (page, errors):
            page.goto(self.live_server_url + reverse("proforma:list"), wait_until="load")
            page.locator('a[href*="mode=modifier"]').click()
            page.wait_for_function("window.FacControlQuickBilling && window.FacControlQuickBilling.active")

            banner = page.locator("#proformaSourceBanner")
            expect(banner).to_contain_text(f"Modification de la Pro-Forma {numero}")
            expect(page.locator("#btnValidateProforma")).to_contain_text("Enregistrer la Pro-Forma")
            expect(page.locator(".comment-input").first).to_have_value("Livraison au bureau")
            quantity = page.locator('#cartTableBody [data-line-key] [data-quick-field="quantity"]').first
            quantity.fill("5")
            quantity.press("Tab")
            expect(quantity).to_have_value("5,000")
            page.screenshot(path=str(self.qa_dir / "proforma-pos-edit.png"))

            # Facturer (Ctrl+Entree) est refuse tant que la modification n'est pas enregistree.
            page.keyboard.press("Control+Enter")
            alert = page.locator(".faccontrol-popup-root, .swal2-popup").filter(has_text="Ce panier modifie une Pro-Forma")
            expect(alert).to_be_visible()
            page.keyboard.press("Escape")
            expect(alert).to_be_hidden()

            # Billing rapide : le bouton Pro-Forma est dans les actions secondaires, F8 l'actionne.
            page.keyboard.press("F8")
            page.wait_for_url(re.compile(r".*/proformas/\d+/\?updated=1"))
            expect(page.locator("#printArea")).to_contain_text(numero)
            self.assertFalse(errors)

        self.proforma.refresh_from_db()
        self.assertEqual(self.proforma.numero, numero)
        self.assertEqual(self.proforma.lignes.get(produit=self.product).quantite, Decimal("5.000"))
        self.assertEqual(Commande.objects.count(), 0)

    def test_banner_warns_when_point_de_vente_prices_changed(self):
        from playwright.sync_api import expect

        ProduitPointVentePrix.objects.create(
            produit=self.product, conditionnement=self.base_packaging, point_de_vente=self.pdv, prix_vente=Decimal("12000"),
        )
        with self.browser() as (page, errors):
            page.goto(self.live_server_url + f"{reverse('facturation:pos-view')}?proforma={self.proforma.pk}", wait_until="load")
            banner = page.locator("#proformaSourceBanner")
            expect(banner).to_contain_text("diffère de la Pro-Forma")
            expect(banner).to_have_class(re.compile(r"\balert-warning\b"))
            # Le rattachement peut etre retire : la vente devient une facture ordinaire.
            banner.locator(".btn-close").click()
            expect(banner).to_be_hidden()
            self.assertEqual(page.evaluate("ACTIVE_PROFORMA"), None)
            self.assertFalse(errors)
