"""G_Scan dans Chrome : douchette, camera et informations produit sur le vrai POS."""
import base64
import importlib.util
import time
from pathlib import Path
from unittest import skipUnless

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 facturation import tests_quick_billing_browser as quick_browser
from facturation.models import Produit, UserPermissionBouton

from .models import LecteurCodeBarres

FIXTURES = Path(__file__).resolve().parent / "test_fixtures"

# Camera simulee : un canvas devient le flux video. `window.__camera` pilote
# le test (code "vu", erreur a lever, image a filmer) et garde les pistes.
FAKE_CAMERA = """
(() => {
  const state = window.__camera = {code: null, format: 'ean_13', error: null, tracks: [], imageSrc: null};
  if (!navigator.mediaDevices) return;
  navigator.mediaDevices.getUserMedia = async () => {
    if (state.error) throw new DOMException('Refus simule', state.error);
    const canvas = document.createElement('canvas');
    canvas.width = 640;
    canvas.height = 480;
    const context = canvas.getContext('2d');
    let image = null;
    if (state.imageSrc) {
      image = new Image();
      image.src = state.imageSrc;
      await image.decode();
    }
    const stream = canvas.captureStream(30);
    const paint = () => {
      context.fillStyle = '#ffffff';
      context.fillRect(0, 0, canvas.width, canvas.height);
      if (image) context.drawImage(image, (canvas.width - image.width) / 2, (canvas.height - image.height) / 2);
      if (stream.getVideoTracks().some((track) => track.readyState === 'live')) requestAnimationFrame(paint);
    };
    paint();
    state.tracks.push(...stream.getTracks());
    return stream;
  };
  navigator.mediaDevices.enumerateDevices = async () => [
    {kind: 'videoinput', deviceId: 'fake-camera', label: 'Camera de test', groupId: 'g'},
  ];
})();
"""

# Decodeur simule : "lit" le code place par le test dans window.__camera.
FAKE_DETECTOR = """
window.BarcodeDetector = class {
  static async getSupportedFormats() { return ['ean_13', 'code_128', 'qr_code']; }
  async detect() {
    const state = window.__camera;
    return state.code ? [{rawValue: state.code, format: state.format}] : [];
  }
};
"""

TRACKS_ENDED = "window.__camera.tracks.length > 0 && window.__camera.tracks.every((track) => track.readyState === 'ended')"

# Son simule : chaque bip garde sa frequence (1000 Hz = trouve, 320 Hz = erreur).
BEEP_SPY = """
window.__beeps = [];
window.AudioContext = class {
  constructor() { this.state = 'running'; this.currentTime = 0; this.destination = {}; }
  resume() {}
  close() { return Promise.resolve(); }
  createGain() { return {gain: {value: 0}, connect: (node) => node}; }
  createOscillator() {
    const oscillator = {type: '', frequency: {value: 0}, connect: (node) => node, stop() {},
      start() { window.__beeps.push(oscillator.frequency.value); }};
    return oscillator;
  }
};
"""

# Banc d'essai de la douchette : CDP n'envoie une touche qu'une fois la
# precedente traitee, et une machine chargee peut alors depasser les 120 ms de
# silence qui terminent une rafale, ce qu'une vraie douchette (touches en file
# d'attente) ne fait pas. Les scans de ces tests finissent tous par Entree :
# allonger ce silence ne change rien a ce qui est verifie.
STEADY_KEYBOARD = "window.GScan = Object.assign(window.GScan || {}, {config: {keyboard: {settle: 400}}});"

@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests Chrome.")
class GScanBrowserTests(StaticLiveServerTestCase):
    browser = quick_browser.QuickBillingBrowserTests.browser
    assert_focus = quick_browser.QuickBillingBrowserTests.assert_focus

    def setUp(self):
        quick_browser.QuickBillingBrowserTests.setUp(self)
        # La camera du POS n'est jamais accordee par defaut : le super
        # administrateur l'autorise explicitement pour ce caissier.
        UserPermissionBouton.objects.create(
            user=self.user, module="point_de_vente", bouton="show_camera_scan_button", label="Camera", autorise=True,
        )
        cache.clear()

    def see(self, page, code, format="ean_13"):
        page.evaluate("([code, format]) => { window.__camera.code = code; window.__camera.format = format; }", [code, format])

    def scan_with_keyboard(self, page, code):
        """Une douchette tape le code d'une traite puis envoie Entree.

        Les touches partent avec l'horodatage d'une vraie rafale (5 ms
        d'ecart), comme celles d'une douchette que le systeme horodate a la
        frappe : avec `page.keyboard.type`, un rendu de la page pouvait
        espacer deux touches de plus de 50 ms et couper la rafale.

        CDP n'envoie une touche qu'une fois la precedente traitee : on laisse
        d'abord la page finir l'article precedent (150 ms, le temps de saisir
        l'article suivant a la caisse), sinon un rendu en cours etirerait la
        rafale au-dela du silence qui la termine (120 ms). Une vraie douchette
        n'a pas ce defaut : ses touches attendent en file pendant un rendu.
        """
        page.evaluate("new Promise((resolve) => setTimeout(() => requestAnimationFrame(() => resolve()), 150))")
        session = page.context.new_cdp_session(page)
        start = time.time()
        keys = [{"key": char, "text": char} for char in code]
        keys.append({"key": "Enter", "code": "Enter", "text": "\r", "windowsVirtualKeyCode": 13})
        try:
            for index, key in enumerate(keys):
                stamp = start + index * 0.005
                session.send("Input.dispatchKeyEvent", {"type": "keyDown", "timestamp": stamp, **key})
                up = {name: value for name, value in key.items() if name != "text"}
                session.send("Input.dispatchKeyEvent", {"type": "keyUp", "timestamp": stamp + 0.001, **up})
        finally:
            session.detach()

    def close_popup(self, page, message):
        """Les messages Django s'affichent en popup : on la lit puis on la ferme."""
        from playwright.sync_api import expect

        popup = page.locator(".faccontrol-popup-root.is-open")
        expect(popup).to_contain_text(message)
        popup.get_by_role("button").first.click()
        expect(popup).to_have_count(0)

    def test_keyboard_scanner_adds_products_from_any_field_without_polluting_it(self):
        from playwright.sync_api import expect

        Produit.objects.filter(pk=self.product.pk).update(code_barres="6001234567890")
        with self.browser(keyboard_scanner=True, init_script=STEADY_KEYBOARD) as page:
            rows = page.locator("#cartTableBody .cart-row")
            quantities = page.locator('[data-quick-field="quantity"]')
            feedback = page.locator("#posScanFeedback")
            search = page.locator("#productSearchInput")
            self.assert_focus(page, "#productSearchInput")

            self.scan_with_keyboard(page, "6001234567890")
            expect(rows).to_have_count(1)
            expect(feedback).to_contain_text("PEMPASE")
            expect(search).to_have_value("")
            self.scan_with_keyboard(page, "6001234567890")
            expect(quantities.first).to_have_value("2,000")

            # Curseur dans une quantite : le scan ajoute sans y taper le code.
            quantities.first.focus()
            self.scan_with_keyboard(page, "6001234567890")
            expect(quantities.first).to_have_value("3,000")

            # Code d'un conditionnement : c'est le carton qui entre au panier.
            self.scan_with_keyboard(page, "PEM12")
            expect(rows).to_have_count(2)
            expect(rows.nth(1)).to_contain_text("Carton")

            # Code inconnu : message et creation du produit avec ce code prerempli.
            self.scan_with_keyboard(page, "9990001112223")
            expect(feedback).to_contain_text("9990001112223")
            feedback.get_by_role("button").click()
            expect(page.locator("#quickProductModal")).to_be_visible()
            expect(page.locator("#quickProductBarcode")).to_have_value("9990001112223")
            self.assert_focus(page, "#quickProductName")
            page.keyboard.press("Escape")
            expect(page.locator("#quickProductModal")).to_be_hidden()

            # Frappe humaine : rien n'est intercepte.
            search.focus()
            page.keyboard.type("pem", delay=150)
            expect(search).to_have_value("pem")
            expect(rows).to_have_count(2)

            page.locator("#posVisualMode").click()
            # Grille du POS visuel chargee avant de scanner : CDP n'envoie la
            # touche suivante qu'une fois la precedente traitee, la page occupee
            # a dessiner etirerait la rafale (une vraie douchette, elle, met ses
            # touches en file d'attente pendant ce temps).
            page.wait_for_function(
                "!window.FacControlQuickBilling.active && window.FacControlQuickBilling.visualLoaded"
                " && !window.FacControlQuickBilling.visualLoading"
            )
            self.scan_with_keyboard(page, "JUS-INCONNU-0")
            expect(feedback).to_contain_text("JUS-INCONNU-0")
            self.scan_with_keyboard(page, "GEDETEST02")
            expect(page.locator("#cartTableBody .cart-row")).to_have_count(3)
            expect(feedback).to_contain_text("JUS MANGO")

    def test_product_catalogue_keyboard_scanner_searches_without_click(self):
        """Le catalogue ecoute la douchette en permanence, comme le Billing POS."""

        from playwright.sync_api import expect

        barcode = "6001234567890"
        Produit.objects.filter(pk=self.product.pk).update(code_barres=barcode)
        with self.browser(keyboard_scanner=True, init_script=STEADY_KEYBOARD) as page:
            page.goto(self.live_server_url + reverse("facturation:produit-list"), wait_until="load")
            search = page.locator("#product-live-search-input")
            rows = page.locator("#product-results-table tbody tr")

            # Aucun clic dans la barre : le scan fonctionne meme depuis les filtres.
            page.locator("#product-category-filter").focus()
            self.scan_with_keyboard(page, barcode)

            expect(search).to_have_value(barcode)
            expect(rows).to_have_count(1)
            expect(rows.first).to_contain_text("PEMPASE")
            expect(page.locator("#product-usb-scan-toggle")).to_have_count(0)

    def test_keyboard_scan_in_a_quantity_field_never_changes_that_quantity(self):
        """Curseur dans une quantite : la page ne voit jamais le 1er chiffre du code.

        Le POS valide une quantite 100 ms apres la frappe ; une douchette met
        ~130 ms pour un EAN-13 et Entree. Si la page voyait "62" (1er chiffre
        du code devant la quantite 2), elle l'enregistrerait et redessinerait
        la ligne avant la fin du scan : quantite faussee (63). On observe donc
        ce que voient les ecouteurs de la page, quel que soit le rythme.
        """
        from playwright.sync_api import expect

        Produit.objects.filter(pk=self.product.pk).update(code_barres="6001234567890")
        with self.browser(keyboard_scanner=True, init_script=STEADY_KEYBOARD) as page:
            quantities = page.locator('[data-quick-field="quantity"]')
            self.assert_focus(page, "#productSearchInput")
            self.scan_with_keyboard(page, "6001234567890")
            expect(quantities.first).to_have_value("1,000")
            # Ecouteur de la page, comme celui du POS (phase de bouillonnement).
            page.evaluate("""() => {
                window.__seen = [];
                document.addEventListener('input', (event) => {
                    if (event.target.dataset.quickField === 'quantity') window.__seen.push(event.target.value);
                });
            }""")
            for expected in ("2,000", "3,000", "4,000"):
                quantities.first.focus()
                self.scan_with_keyboard(page, "6001234567890")
                expect(quantities.first).to_have_value(expected)
            self.assertFalse(
                [value for value in page.evaluate("window.__seen") if value.startswith("6") or len(value) > 1],
                page.evaluate("window.__seen"),
            )
            page.wait_for_timeout(250)
            expect(quantities.first).to_have_value("4,000")
            expect(page.locator("#cartTableBody .cart-row")).to_have_count(1)

            # Frappe humaine dans la quantite : toujours prise en compte.
            quantities.first.focus()
            quantities.first.press("Control+a")
            page.keyboard.type("7", delay=150)
            page.wait_for_timeout(400)
            quantities.first.press("Tab")
            expect(quantities.first).to_have_value("7,000")

    def test_camera_beeps_and_closes_after_each_product_and_hands_back_unknown_codes(self):
        from playwright.sync_api import expect

        # Codes EAN a cle GS1 valide : la camera ecarte une lecture dont la cle est fausse.
        Produit.objects.filter(pk=self.product.pk).update(code_barres="6001234567899")
        with self.browser(init_script=FAKE_CAMERA + FAKE_DETECTOR + BEEP_SPY) as page:
            rows = page.locator("#cartTableBody .cart-row")
            quantities = page.locator('[data-quick-field="quantity"]')
            modal = page.locator("#cameraScanModal")
            status = modal.locator(".fc-camera-status")

            def scan(code, format="ean_13"):
                self.see(page, None)
                page.locator("#cameraScanToggle").click()
                expect(modal).to_be_visible()
                expect(status).to_have_text("Placez le code-barres dans le cadre.")
                self.see(page, code, format)

            # Produit trouve : un seul bip (la confirmation, pas la lecture),
            # message visible, puis la camera disparait pour l'article suivant.
            scan("6001234567899")
            expect(rows).to_have_count(1)
            expect(status).to_contain_text("PEMPASE")
            page.screenshot(path=str(self.qa_dir / "gscan-camera-found.png"))
            expect(modal).to_be_hidden()
            self.assertEqual(page.evaluate("window.__beeps"), [1000])
            page.wait_for_function(TRACKS_ENDED)
            self.assert_focus(page, "#productSearchInput")

            # Nouvelle ouverture pour le meme produit : deuxieme article.
            scan("6001234567899")
            expect(quantities.first).to_have_value("2,000")
            expect(modal).to_be_hidden()

            scan("PEM12", "code_128")
            expect(rows).to_have_count(2)
            expect(rows.nth(1)).to_contain_text("Carton")
            expect(modal).to_be_hidden()
            self.assertEqual(page.evaluate("window.__beeps"), [1000, 1000, 1000])

            # Code inconnu : bip d'erreur, la camera se ferme, le POS propose de creer le produit.
            scan("9990001112226")
            expect(modal).to_be_hidden()
            self.assertEqual(page.evaluate("window.__beeps")[-1], 320)
            feedback = page.locator("#posScanFeedback")
            expect(feedback).to_contain_text("9990001112226")
            expect(feedback.get_by_role("button")).to_be_visible()
            page.wait_for_function(TRACKS_ENDED)
            self.assertEqual(page.locator(".fc-camera").count(), 0)

    def test_camera_denied_message_and_field_camera_fills_barcode_without_selling(self):
        from playwright.sync_api import expect

        with self.browser(init_script=FAKE_CAMERA + FAKE_DETECTOR) as page:
            modal = page.locator("#cameraScanModal")
            page.evaluate("window.__camera.error = 'NotAllowedError'")
            page.locator("#cameraScanToggle").click()
            expect(modal.locator(".fc-camera-status")).to_contain_text("Autorisez la caméra")
            page.screenshot(path=str(self.qa_dir / "gscan-camera-denied.png"))
            modal.locator(".btn-close").click()
            expect(modal).to_be_hidden()
            page.evaluate("window.__camera.error = null")

            # Bouton camera du champ code-barres de "Ajouter produit" : lecture
            # unique, a l'interieur de la modale, sans rien vendre.
            page.locator('button[data-bs-target="#quickProductModal"]').click()
            product_modal = page.locator("#quickProductModal")
            expect(product_modal).to_be_visible()
            product_modal.locator("[data-barcode-camera]").click()
            overlay = product_modal.locator(".fc-camera-overlay.is-inline")
            expect(overlay).to_be_visible()
            self.see(page, "4006381333931")
            expect(page.locator("#quickProductBarcode")).to_have_value("4006381333931")
            expect(overlay).to_have_count(0)
            self.assert_focus(page, "#quickProductBarcode")
            expect(product_modal).to_be_visible()
            expect(page.locator("#cartTableBody .cart-row")).to_have_count(0)
            page.wait_for_function(TRACKS_ENDED)

    def test_camera_decodes_real_ean13_with_vendored_polyfill_loaded_on_demand(self):
        from playwright.sync_api import expect

        Produit.objects.filter(pk=self.product.pk).update(code_barres="6001234567899")
        image = base64.b64encode((FIXTURES / "ean13-6001234567899.png").read_bytes()).decode()
        # Pas de decodeur simule : Chrome Windows n'a pas d'API native, c'est
        # donc le polyfill zxing-wasm vendorise qui lit l'image filmee.
        real_decoder = f"window.__camera.imageSrc = 'data:image/png;base64,{image}'; delete window.BarcodeDetector;"
        with self.browser(init_script=FAKE_CAMERA + real_decoder) as page:
            loaded = "performance.getEntriesByType('resource').some((entry) => entry.name.includes('barcode-detector-ponyfill'))"
            self.assertFalse(page.evaluate(loaded))
            page.locator("#cameraScanToggle").click()
            expect(page.locator("#cartTableBody .cart-row")).to_have_count(1, timeout=30000)
            expect(page.locator("#cartTableBody .cart-row")).to_contain_text("PEMPASE")
            self.assertTrue(page.evaluate(loaded))
            self.assertTrue(page.evaluate(
                "performance.getEntriesByType('resource').some((entry) => entry.name.includes('zxing_reader.wasm'))"
            ))
            page.screenshot(path=str(self.qa_dir / "gscan-camera-real-decode.png"))

    def test_scanner_management_page_tests_keyboard_and_camera_scans(self):
        from playwright.sync_api import expect

        Produit.objects.filter(pk=self.product.pk).update(code_barres="6001234567899")
        # Gestion Scanner : reservee au super administrateur.
        get_user_model().objects.filter(pk=self.user.pk).update(is_superuser=True)
        with self.browser(keyboard_scanner=True, init_script=FAKE_CAMERA + FAKE_DETECTOR) as page:
            page.goto(self.live_server_url + reverse("gscan:scanner-management"), wait_until="load")
            code = page.locator("#gscanTestCode")
            result = page.locator("#gscanTestResult")
            expect(page.locator("#gscanCameraStatus")).to_contain_text("Disponible")

            # Douchette : scan sans cliquer dans le champ.
            page.locator("#gscan-test-title").click()
            self.scan_with_keyboard(page, "PEM12")
            expect(code).to_have_value("PEM12")
            expect(result).to_contain_text("conditionnement (Carton)")
            expect(result).to_contain_text("PEMPASE")

            # Camera : lecture unique qui remplit et teste le champ.
            page.locator('[data-barcode-camera="#gscanTestCode"]').click()
            overlay = page.locator(".fc-camera-overlay")
            expect(overlay).to_be_visible()
            self.see(page, "6001234567899")
            expect(code).to_have_value("6001234567899")
            expect(result).to_contain_text("code-barres")
            expect(overlay).to_have_count(0)
            page.wait_for_function(TRACKS_ENDED)
            page.screenshot(path=str(self.qa_dir / "gscan-scanner-management.png"), full_page=True)

    def test_scanner_management_detects_a_keyboard_scanner_and_registers_a_camera(self):
        from playwright.sync_api import expect

        get_user_model().objects.filter(pk=self.user.pk).update(is_superuser=True)
        with self.browser(init_script=FAKE_CAMERA + FAKE_DETECTOR) as page:
            page.goto(self.live_server_url + reverse("gscan:scanner-management"), wait_until="load")
            status = page.locator("#gscanDetectStatus")
            readers = page.locator("#gscanLecteurs")
            expect(page.locator("#gscanNoLecteur")).to_be_visible()

            # Frappe humaine : ce n'est pas une douchette.
            page.locator("#gscanDetectKeyboard").click()
            expect(status).to_contain_text("Scannez maintenant")
            page.keyboard.type("123456", delay=150)
            page.keyboard.press("Enter")
            expect(status).to_contain_text("Frappe trop lente")

            # Douchette : rafale rapide terminee par Entree, rien n'est tape ailleurs.
            page.locator("#gscanDetectKeyboard").click()
            page.keyboard.type("6001234567890")
            page.keyboard.press("Enter")
            expect(status).to_contain_text("Douchette détectée : code 6001234567890")
            expect(page.locator("#id_lecteur-type_lecteur")).to_have_value("douchette")
            expect(page.locator("#id_lecteur-suffixe")).to_have_value("entree")
            speed = int(page.locator("#id_lecteur-vitesse_ms").input_value())
            self.assertTrue(1 <= speed <= 80, speed)
            expect(page.locator("#id_lecteur-appareil")).to_be_hidden()
            expect(page.locator("#gscanTestCode")).to_have_value("")
            self.assert_focus(page, "#id_lecteur-nom")
            page.locator("#id_lecteur-nom").fill("Caisse 1")
            page.locator("#id_lecteur-par_defaut").check()
            page.locator("#gscanSaveLecteur").click()
            self.close_popup(page, "Lecteur « Caisse 1 » enregistré.")
            expect(readers).to_contain_text("Caisse 1")
            expect(page.locator("#gscanDefaultDouchette")).to_have_text("Caisse 1")
            # Les reglages mesures sont publies a chaque page.
            self.assertEqual(page.evaluate("window.GScan.config.keyboard.endKeys"), ["Enter"])

            # Camera branchee sur cet ordinateur.
            page.locator("#gscanDetectCamera").click()
            choice = page.get_by_role("radio", name="Camera de test")
            expect(choice).to_be_visible()
            choice.check()
            expect(page.locator("#id_lecteur-type_lecteur")).to_have_value("camera")
            expect(page.locator("#id_lecteur-appareil")).to_have_value("Camera de test")
            expect(page.locator("#id_lecteur-vitesse_ms")).to_be_hidden()
            # Ajouter un lecteur ne touche pas aux parametres de la page.
            expect(page.locator(".fc-settings-savebar")).to_contain_text("Aucune modification en attente.")
            page.locator("#id_lecteur-par_defaut").check()
            page.screenshot(path=str(self.qa_dir / "gscan-management-add-camera.png"), full_page=True)
            page.locator("#gscanSaveLecteur").click()
            self.close_popup(page, "Lecteur « Camera de test » enregistré.")
            expect(page.locator("#gscanDefaultCamera")).to_have_text("Camera de test")
            self.assertEqual(page.evaluate("window.GScan.config.camera.label"), "Camera de test")
            page.screenshot(path=str(self.qa_dir / "gscan-management-readers.png"), full_page=True)

            # Suppression apres confirmation.
            page.once("dialog", lambda dialog: dialog.accept())
            readers.locator("tr", has_text="Camera de test").get_by_role("button", name="Supprimer").click()
            self.close_popup(page, "Lecteur « Camera de test » supprimé.")
            expect(readers).not_to_contain_text("Camera de test")
            expect(readers).to_contain_text("Caisse 1")
        self.assertEqual(list(LecteurCodeBarres.objects.values_list("nom", flat=True)), ["Caisse 1"])

    def test_scanner_management_settings_in_english(self):
        from playwright.sync_api import expect

        get_user_model().objects.filter(pk=self.user.pk).update(is_superuser=True)
        with self.browser(language="en") as page:
            page.goto(self.live_server_url + reverse("gscan:scanner-management"), wait_until="load")
            expect(page.locator(".fc-settings-nav")).to_contain_text("Registered readers")
            savebar = page.locator(".fc-settings-savebar")
            page.locator("#id_delai_relecture_ms").fill("2500")
            expect(savebar).to_contain_text("Unsaved changes.")
            savebar.get_by_role("button", name="Save settings").click()
            expect(page.locator("#id_delai_relecture_ms")).to_have_value("2500")
            expect(page.locator("#gscan-services")).to_have_count(0)
            page.screenshot(path=str(self.qa_dir / "gscan-management-en.png"), full_page=True)
