"""Parcours Chrome de G_Erreur : notification d'un 504 et catalogue publie des codes."""

import importlib.util
import os
import tempfile
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 .models import Erreur


@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests Chrome.")
class GErreurBrowserTests(StaticLiveServerTestCase):
    def setUp(self):
        cache.clear()
        self.user = get_user_model().objects.create_superuser(username="super", email="super@example.com", password="Super-123")
        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-gerreur-qa"))
        self.qa_dir.mkdir(parents=True, exist_ok=True)

    def browser(self, language="fr"):
        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=language, 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": language, "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:
                    yield page, errors
                finally:
                    context.close()
                    browser.close()
        return session()

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

        with self.browser() as (page, errors):
            page.goto(self.live_server_url + reverse("gerreur:tableau-de-bord"), wait_until="load")
            # nginx renvoie une page HTML 504 quand Django ne repond pas a temps.
            page.route("**/demo/vente/", lambda route: route.fulfill(status=504, content_type="text/html", body="<h1>504 Gateway Time-out</h1>")
                       if route.request.method == "POST" else route.continue_())
            page.evaluate("fetch('/demo/vente/', {method: 'POST'})")
            toast = page.locator(".gerreur-toast")
            expect(toast).to_be_visible()
            expect(toast).to_contain_text("Erreur 504")
            expect(toast).to_contain_text("Délai de réponse dépassé")
            expect(toast).to_contain_text("Ventes & Factures")
            page.screenshot(path=str(self.qa_dir / "gerreur-toast-504.png"))
            page.wait_for_function("!localStorage.getItem('gerreur:rapports') || localStorage.getItem('gerreur:rapports') === '[]'")
            self.assertFalse(errors)

        erreur = Erreur.objects.get(source=Erreur.NAVIGATEUR)
        self.assertEqual((erreur.code, erreur.chemin, erreur.methode), (504, "/demo/vente/", "POST"))

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

        with self.browser() as (page, errors):
            page.goto(self.live_server_url + reverse("gerreur:tableau-de-bord"), wait_until="load")
            page.evaluate("fetch('/demo/vente/en-attente/sauvegarder/', {method: 'POST', headers: {'X-CSRFToken': document.cookie.match(/csrftoken=([^;]+)/)[1], 'Content-Type': 'application/json'}, body: '{}'})")
            page.wait_for_timeout(500)
            expect(page.locator(".gerreur-toast")).to_have_count(0)
            self.assertFalse(errors)

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

        with self.browser() as (page, errors):
            page.goto(self.live_server_url + reverse("gerreur:codes"), wait_until="load")
            expect(page.locator(".gerreur-publication h3")).to_contain_text("v1.0")
            page.screenshot(path=str(self.qa_dir / "gerreur-catalogue.png"), full_page=False)
            page.locator("#gerreur-search").fill("montant")
            expect(page.locator("#code-emcf-50")).to_be_visible()
            expect(page.locator("#code-http-404")).to_have_count(0)
            page.screenshot(path=str(self.qa_dir / "gerreur-catalogue-recherche.png"), full_page=False)
            with page.expect_download() as telechargement:
                page.get_by_role("link", name="Exporter Excel").click()
            self.assertTrue(telechargement.value.suggested_filename.endswith(".xlsx"))
            self.assertFalse(errors)

        with self.browser(language="en") as (page, errors):
            page.goto(self.live_server_url + reverse("gerreur:codes") + "?famille=mcf", wait_until="load")
            expect(page.locator("#code-mcf-nak")).to_contain_text("Message badly received by the MCF")
            page.screenshot(path=str(self.qa_dir / "gerreur-catalogue-en.png"), full_page=False)
            self.assertFalse(errors)
