"""Douchette reglee en QWERTY sur un PC en AZERTY, et lectures camera a cle GS1 fausse."""

import importlib.util
import os
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.test import TestCase
from django.urls import reverse

from dgi.models import ItemType, TaxGroup
from facturation.models import Configuration, PointDeVente, Produit, StockPointDeVente

from .services import normalize_code

EAN = "6915567720602"
EAN_EN_AZERTY = "-ç&((-èèéà-àé"


class DispositionServeurTests(TestCase):
    def test_digit_row_symbols_become_digits_but_mixed_codes_are_kept(self):
        self.assertEqual(normalize_code(EAN_EN_AZERTY), EAN)
        self.assertEqual(normalize_code(" -ç&( "), "6915")
        for code in ("SKU-PF-001", "AB-12", "--", "à&"):
            with self.subTest(code=code):
                self.assertEqual(normalize_code(code), code)

    def test_scan_lookup_finds_the_product_from_the_garbled_code(self):
        pdv = PointDeVente.objects.create(nom="PDV Central")
        user = get_user_model().objects.create_superuser(username="super", email="super@example.com", password="Super-123")
        user.point_de_vente = pdv
        user.save(update_fields=["point_de_vente"])
        Configuration.objects.create(taux_change=Decimal("1"), mode_dgi="ttc", type_dgi="FV")
        produit = Produit.objects.create(nom="Energy 330ml", code_sku="EN330", code_barres=EAN, prix_vente=1000)
        self.client.force_login(user)

        reponse = self.client.get(reverse("gscan:lookup"), {"code": EAN_EN_AZERTY})

        self.assertEqual(reponse.status_code, 200)
        self.assertEqual([item["id"] for item in reponse.json()["results"]], [produit.pk])


@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests Chrome.")
class DispositionNavigateurTests(StaticLiveServerTestCase):
    def setUp(self):
        cache.clear()
        self.pdv = PointDeVente.objects.create(nom="PDV Central")
        self.user = get_user_model().objects.create_superuser(username="super", email="super@example.com", password="Super-123")
        self.user.point_de_vente = self.pdv
        self.user.save(update_fields=["point_de_vente"])
        Configuration.objects.create(nom_entreprise="FacControl", taux_change=Decimal("1"), mode_dgi="ttc", type_dgi="FV")
        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.produit = Produit.objects.create(
            nom="Energy 330ml", code_sku="EN330", code_barres=EAN, prix_vente=1000, taxgroup=group, typeart=kind,
        )
        StockPointDeVente.objects.create(produit=self.produit, point_de_vente=self.pdv, quantite=10)
        self.client.force_login(self.user)
        self.session_value = self.client.cookies[settings.SESSION_COOKIE_NAME].value

    def test_qwerty_scanner_on_azerty_pc_adds_the_right_product(self):
        from playwright.sync_api import expect, sync_playwright

        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": 1366, "height": 768}, locale="fr", service_workers="block")
            context.add_cookies([{"name": settings.SESSION_COOKIE_NAME, "value": self.session_value, "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)))
            try:
                page.goto(self.live_server_url + reverse("facturation:pos-view") + "?billing=quick", wait_until="load")
                page.wait_for_function("window.FacControlQuickBilling && window.FacControlQuickBilling.active")

                # Douchette en QWERTY : touches chiffres sans Maj, le PC AZERTY en fait des symboles.
                page.evaluate("""([texte, codes]) => {
                    const cible = document.activeElement || document.body;
                    const frappe = (key, code) => cible.dispatchEvent(new KeyboardEvent('keydown', {key, code, bubbles: true, cancelable: true}));
                    [...texte].forEach((char, index) => frappe(char, codes[index]));
                    frappe('Enter', 'Enter');
                }""", [EAN_EN_AZERTY, [f"Digit{digit}" for digit in EAN]])
                ligne = page.locator("#cartTableBody [data-line-key]")
                expect(ligne).to_have_count(1)
                expect(ligne.first).to_contain_text("Energy 330ml")

                resultats = page.evaluate("""() => ({
                    // Douchette reglee comme le PC (AZERTY) : chiffres avec Maj, tiret sans Maj -> garde tel quel.
                    azerty: GScan.decodeStrokes([
                        {key: 'S', code: 'KeyS', shift: true}, {key: 'K', code: 'KeyK', shift: true}, {key: 'U', code: 'KeyU', shift: true},
                        {key: '-', code: 'Digit6', shift: false}, {key: '0', code: 'Digit0', shift: true}, {key: '1', code: 'Digit1', shift: true},
                    ]),
                    // Douchette QWERTY avec lettres : lettres relues sur la touche physique (A/Q et Z/W echanges en AZERTY).
                    qwerty: GScan.decodeStrokes([
                        {key: 'Q', code: 'KeyA', shift: true}, {key: 'W', code: 'KeyZ', shift: true},
                        {key: 'à', code: 'Digit0', shift: false}, {key: '&', code: 'Digit1', shift: false},
                    ]),
                    champ: GScan.fixAzertyDigits('-ç&((-èèéà-àé'),
                    champMixte: GScan.fixAzertyDigits('AB-12'),
                })""")
                self.assertEqual(resultats, {"azerty": "SKU-01", "qwerty": "AZ01", "champ": EAN, "champMixte": "AB-12"})
                self.assertFalse(errors)
            finally:
                context.close()
                browser.close()

    def test_camera_rejects_reads_with_a_wrong_gs1_check_digit(self):
        from playwright.sync_api import sync_playwright

        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(service_workers="block")
            context.add_cookies([{"name": settings.SESSION_COOKIE_NAME, "value": self.session_value, "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())
            try:
                page.goto(self.live_server_url + reverse("facturation:pos-view"), wait_until="load")
                page.wait_for_function("typeof (window.GScan && window.GScan.plausibleRead) === 'function'")
                resultats = page.evaluate("""() => [
                    GScan.plausibleRead({code: '401225415593', format: 'itf'}),
                    GScan.plausibleRead({code: '401225415593', format: 'upc_a'}),
                    GScan.plausibleRead({code: '6915567720602', format: 'ean_13'}),
                    GScan.plausibleRead({code: 'SKU-PF-001', format: 'code_128'}),
                ]""")
                self.assertEqual(resultats, [False, False, True, True])
            finally:
                context.close()
                browser.close()
