"""Parcours Chrome de la page Affectation Produit (categorie cochee, apercu, confirmation sans rechargement)."""

import importlib.util
import os
import tempfile
from decimal import Decimal
from pathlib import Path
from unittest import skipUnless

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 Categorie, PointDeVente, Produit, StockPointDeVente

from .models import AffectationProduitPDV


@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests Chrome.")
class AffectationBrowserTests(StaticLiveServerTestCase):
    def setUp(self):
        # Sous Windows, MySQL stocke les tables « G_Affectation_* » en minuscules :
        # le flush de TransactionTestCase ne les reconnait pas et les garde.
        from .models import MentionPointDeVente, OperationAffectation, ParametrePointDeVente
        OperationAffectation.objects.all().delete()
        AffectationProduitPDV.objects.all().delete()
        ParametrePointDeVente.objects.all().delete()
        MentionPointDeVente.objects.all().delete()
        cache.clear()
        self.gombe = PointDeVente.objects.create(nom="Gombe")
        self.limete = PointDeVente.objects.create(nom="Limete")
        tax, _ = TaxGroup.objects.update_or_create(code="B", defaults={"name": "Taxable", "tax": Decimal("16")})
        item, _ = ItemType.objects.get_or_create(code="BIE", defaults={"name": "Bien"})
        self.boissons = Categorie.objects.create(nom="Boissons")
        savons = Categorie.objects.create(nom="Savons")
        # 60 boissons : plus d'une page (50) pour verifier la selection des produits non affiches.
        self.produits = [Produit.objects.create(code_sku=f"BOI{index:03d}", nom=f"Boisson {index:02d}", categorie=self.boissons,
                                                typeart=item, taxgroup=tax, prix_vente=Decimal("1000")) for index in range(60)]
        for index in range(3):
            Produit.objects.create(code_sku=f"SAV{index:03d}", nom=f"Savon {index}", categorie=savons, typeart=item, taxgroup=tax, prix_vente=500)
        StockPointDeVente.objects.create(point_de_vente=self.gombe, produit=self.produits[0], quantite=Decimal("8"), cump=Decimal("400"))
        self.user = get_user_model().objects.create_user(username="admin-qa", email="admin-qa@test.local", password="Admin-123", role="ADMIN", point_de_vente=self.gombe)
        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-affectation-qa"))
        self.qa_dir.mkdir(parents=True, exist_ok=True)

    def _browser(self, 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)
        return playwright.chromium.launch(headless=True, **({"executable_path": executable} if executable else {}))

    def _page(self, browser, langue="fr", largeur=1440, hauteur=900):
        context = browser.new_context(viewport={"width": largeur, "height": hauteur}, locale=langue, 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": langue, "url": self.live_server_url},
        ])
        page = context.new_page()
        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)))
        return context, page, errors

    def test_categorie_cochee_apercu_et_confirmation_sans_rechargement(self):
        from playwright.sync_api import expect, sync_playwright

        with sync_playwright() as playwright:
            browser = self._browser(playwright)
            try:
                context, page, errors = self._page(browser)
                page.goto(self.live_server_url + reverse("facturation:dashboard"), wait_until="load")
                # Depuis le menu Administration (section repliee au depart).
                lien = page.locator(f'a[href="{reverse("gaffectation:page")}"]').first
                page.locator("#sidebar .sidebar-section-toggle", has_text="Administration").first.click()
                expect(lien).to_be_visible()
                lien.click()
                page.wait_for_url("**" + reverse("gaffectation:page"))
                page.evaluate("window.__sansRechargement = true")
                section = page.locator('.gaff-category[data-categorie="%s"]' % self.boissons.pk)
                expect(section).to_contain_text("0 / 60")
                section.locator("[data-category-toggle]").click()
                expect(section.locator("[data-product]")).to_have_count(50)

                # La case de categorie prend aussi les 10 produits pas encore affiches.
                section.locator("[data-category-check]").check()
                expect(page.locator("#gaffSelectedCount")).to_contain_text("60")
                expect(section).to_contain_text("60 / 60")
                section.locator("[data-more]").click()
                expect(section.locator("[data-product]")).to_have_count(60)
                self.assertTrue(section.locator(f'[data-product-check="{self.produits[59].pk}"]').is_checked())
                page.screenshot(path=str(self.qa_dir / "affectation-categorie-cochee-fr.png"), full_page=False)

                # Decocher un produit : la case de categorie devient partielle.
                section.locator(f'[data-product-check="{self.produits[1].pk}"]').uncheck()
                self.assertTrue(section.locator("[data-category-check]").evaluate("box => box.indeterminate"))
                expect(page.locator("#gaffSelectedCount")).to_contain_text("59")

                page.select_option("#gaffDestination", f"p:{self.limete.pk}")
                expect(page.locator("#gaffSelectedHere")).to_contain_text("59")
                page.locator("#gaffDeclare").click()
                preview = page.locator("#gaffPreview")
                expect(preview).to_be_visible()
                expect(preview).to_contain_text("Stock positif dans Gombe")
                expect(preview).to_contain_text("vendables dans Limete dès la confirmation, même sans stock")
                self.assertTrue(page.locator("#gaffConfirm").is_enabled())
                page.wait_for_timeout(400)
                page.screenshot(path=str(self.qa_dir / "affectation-apercu-fr.png"))

                page.locator("#gaffConfirm").click()
                expect(page.locator("#gaffResult")).to_contain_text("59 produit(s) déplacé(s) vers Limete")
                expect(preview).to_be_hidden()
                row = section.locator(f'[data-product="{self.produits[0].pk}"]')
                expect(row).to_contain_text("Vendu à Limete")
                expect(section.locator(f'[data-product="{self.produits[1].pk}"]')).to_contain_text("Vendu partout")
                self.assertTrue(page.evaluate("window.__sansRechargement === true"))
                excel = page.locator("#gaffResult a.btn-success")
                self.assertIn(f"pdv={self.limete.pk}&portee_prix=pdv&operation=", excel.get_attribute("href"))
                expect(page.locator("#gaffOperations")).to_contain_text("Limete")
                page.screenshot(path=str(self.qa_dir / "affectation-resultat-fr.png"), full_page=False)
                row.scroll_into_view_if_needed()
                page.wait_for_timeout(1700)
                page.screenshot(path=str(self.qa_dir / "affectation-mentions-mises-a-jour-fr.png"), full_page=False)

                # « PDV de reference Gombe / Pas vendus ici » : les 59 boissons deplacees ;
                # la boisson decochee et les savons, vendus partout, se vendent encore a Gombe.
                page.select_option("#gaffFilterPdv", str(self.gombe.pk))
                page.select_option("#gaffFilterVente", "ailleurs")
                expect(page.locator("#gaffResultCount")).to_contain_text("59 produit(s)")
                expect(page.locator(".gaff-category")).to_have_count(1)
                expect(page.locator(".gaff-category [data-product]").first).to_contain_text("Ne se vend pas ici")

                # POS : Gombe ne propose plus la boisson, Limete la vend sans stock.
                recherche = page.request.get(self.live_server_url + reverse("facturation:search") + "?entity=product&context=pos&q=BOI000").json()
                self.assertEqual(recherche["results"], [])
                self.assertFalse(errors, errors)
                context.close()

                # Telephone 375 px, puis anglais.
                context, page, errors = self._page(browser, "fr", 375, 812)
                page.goto(self.live_server_url + reverse("gaffectation:page"), wait_until="load")
                expect(page.locator(".gaff-category").first).to_be_visible()
                self.assertLessEqual(page.evaluate("document.documentElement.scrollWidth"), 375)
                box = page.locator(".gaff-category [data-category-check]").first.bounding_box()
                self.assertGreaterEqual(box["height"], 24)
                barre = page.locator("#gaffBar").bounding_box()
                self.assertEqual((barre["x"], barre["width"]), (0, 375))
                self.assertGreaterEqual(page.locator("#gaffDeclare").bounding_box()["height"], 44)
                page.screenshot(path=str(self.qa_dir / "affectation-mobile-375-fr.png"), full_page=True)
                self.assertFalse(errors, errors)
                context.close()

                context, page, errors = self._page(browser, "en")
                page.goto(self.live_server_url + reverse("gaffectation:page"), wait_until="load")
                expect(page.locator("#gaff-produits-title")).to_have_text("Products by category")
                expect(page.locator("#gaffDeclare")).to_contain_text("Declare")
                expect(page.locator(".gaff-category").first).to_contain_text("selected")
                page.screenshot(path=str(self.qa_dir / "affectation-en.png"), full_page=False)
                self.assertFalse(errors, errors)
                context.close()
            finally:
                browser.close()
        # Hors de la boucle Playwright (l'ORM refuse un contexte asynchrone).
        self.assertEqual(AffectationProduitPDV.objects.filter(point_de_vente=self.limete).count(), 59)
        self.assertEqual(StockPointDeVente.objects.filter(point_de_vente=self.limete).count(), 59)

    def test_parametrage_mention_puis_declaration_vers_la_mention(self):
        from playwright.sync_api import expect, sync_playwright

        with sync_playwright() as playwright:
            browser = self._browser(playwright)
            try:
                context, page, errors = self._page(browser)
                page.goto(self.live_server_url + reverse("gaffectation:page"), wait_until="load")
                carte = page.locator("#gaff-parametrage")
                carte.scroll_into_view_if_needed()
                page.fill("#gaffMentionName", "Magasin")
                carte.get_by_role("button", name="Ajouter").click()
                expect(page.locator("#gaffMentionList")).to_contain_text("Magasin")
                for point in (self.gombe, self.limete):
                    page.select_option(f'[data-point-mention="{point.pk}"]', label="Magasin")
                    expect(page.locator("#gaffSettingsMessage")).to_contain_text(f"{point.nom} porte maintenant la mention Magasin")
                expect(page.locator("#gaffMentionList")).to_contain_text("2 PDV")
                page.screenshot(path=str(self.qa_dir / "affectation-parametrage-mentions-fr.png"), full_page=False)

                # La mention devient une destination : « Déplacer vers » tous les PDV Magasin.
                section = page.locator('.gaff-category[data-categorie="%s"]' % self.boissons.pk)
                section.locator("[data-category-toggle]").click()
                section.locator(f'[data-product-check="{self.produits[2].pk}"]').check()
                page.select_option("#gaffDestination", label="Mention Magasin (2 PDV)")
                expect(page.locator(".gaff-bar-stock")).to_be_hidden()
                page.locator("#gaffDeclare").click()
                expect(page.locator("#gaffPreview")).to_contain_text("mention Magasin")
                page.locator("#gaffConfirm").click()
                ligne = section.locator(f'[data-product="{self.produits[2].pk}"]')
                expect(ligne).to_contain_text("Vendu dans les PDV « Magasin »")
                expect(page.locator("#gaffResult a.btn-success")).to_have_count(2)
                self.assertFalse(errors, errors)
                context.close()

                context, page, errors = self._page(browser, "en")
                page.goto(self.live_server_url + reverse("gaffectation:page"), wait_until="load")
                expect(page.locator("#gaff-parametrage-title")).to_have_text("Point of sale settings")
                page.locator("#gaff-parametrage").scroll_into_view_if_needed()
                page.screenshot(path=str(self.qa_dir / "affectation-parametrage-mentions-en.png"), full_page=False)
                self.assertFalse(errors, errors)
                context.close()
            finally:
                browser.close()
        self.assertEqual(AffectationProduitPDV.objects.get(produit=self.produits[2]).mention.nom, "Magasin")

