"""G_Scan : informations produit publiques d'un nouveau code-barres.

Aucun appel reseau reel : `requests.get` est remplace par `FakeNetwork`, qui
rejoue des reponses reelles enregistrees dans `test_fixtures/` (Open Food
Facts et UPCitemdb, octobre 2026).
"""
import json
import shutil
import tempfile
from datetime import timedelta
from io import BytesIO
from pathlib import Path
from unittest import mock

import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from PIL import Image

from facturation.models import Categorie, Produit, UserMenuPermission

from .models import InfoProduitExterne, ParametresScanner
from .product_info import (
    GoUpcProvider, attach_external_image, clean_quantity, compose_name, providers_status, suggest_category,
)
from .services import gtin_check_digit_ok, is_internal_gtin
from .tests import GScanTestCase

FIXTURES = Path(__file__).resolve().parent / "test_fixtures"
OFF = "https://world.openfoodfacts.org/api/v2/product/"
UPC = "https://api.upcitemdb.com/prod/trial/lookup"
GO_UPC = "https://go-upc.com/api/v1/code/"
NUTELLA = "3017620422003"
BAVARIA = "8714800050845"
NUTELLA_IMAGE = "https://images.openfoodfacts.org/images/products/301/762/042/2003/front_en.879.400.jpg"


def fixture(name):
    return json.loads((FIXTURES / name).read_text(encoding="utf-8"))


def response(status=200, payload=None, content=b"", headers=None):
    """Reponse `requests` construite en memoire, lisible aussi en streaming."""

    result = requests.Response()
    result.status_code = status
    if payload is not None:
        content = json.dumps(payload).encode()
        headers = {"Content-Type": "application/json", **(headers or {})}
    result._content = content
    result._content_consumed = True
    result.headers.update(headers or {})
    return result


def jpeg_bytes():
    buffer = BytesIO()
    Image.new("RGB", (8, 8), "orange").save(buffer, "JPEG")
    return buffer.getvalue()


def with_check_digit(body):
    total = sum(int(digit) * (3 if index % 2 == 0 else 1) for index, digit in enumerate(reversed(body)))
    return body + str((10 - total % 10) % 10)


class FakeNetwork:
    """Remplace `requests.get` : chaque URL attendue a sa reponse, les autres echouent."""

    def __init__(self):
        self.routes = {}
        self.calls = []

    def __call__(self, url, **kwargs):
        self.calls.append((url, kwargs))
        # La route la plus precise l'emporte (un code donne avant la base entiere).
        prefixes = sorted((prefix for prefix in self.routes if url.startswith(prefix)), key=len, reverse=True)
        if not prefixes:
            raise AssertionError(f"Appel reseau inattendu : {url}")
        result = self.routes[prefixes[0]]
        if isinstance(result, Exception):
            raise result
        return result()

    @property
    def urls(self):
        return [url for url, _kwargs in self.calls]


@override_settings(GSCAN_EXTERNAL_LOOKUP=True, GSCAN_UPCITEMDB_ENABLED=True, GSCAN_GO_UPC_API_KEY="")
class ProductInfoTestCase(GScanTestCase):
    def setUp(self):
        super().setUp()
        self.network = FakeNetwork()
        patcher = mock.patch("G_Scan.product_info.requests.get", self.network)
        patcher.start()
        self.addCleanup(patcher.stop)

    def set_params(self, **values):
        params = ParametresScanner.load()
        for name, value in values.items():
            setattr(params, name, value)
        params.save()

    def route(self, prefix, result):
        self.network.routes[prefix] = result

    def route_json(self, prefix, name, status=200):
        self.route(prefix, lambda: response(status, fixture(name)))

    def info(self, code, expected_status=200):
        result = self.client.get(reverse("gscan:product-info"), {"code": code})
        self.assertEqual(result.status_code, expected_status, result.content)
        return result.json()


class GtinRulesTests(ProductInfoTestCase):
    def test_check_digit_and_internal_codes(self):
        self.assertEqual(with_check_digit("871480005084"), BAVARIA)
        for code in (BAVARIA, NUTELLA, "012345678905", "96385074", "00012345678905"):
            with self.subTest(code=code):
                self.assertTrue(gtin_check_digit_ok(code))
        for code in ("8714800050846", "012345678900", "PEM12", "12345", ""):
            with self.subTest(code=code):
                self.assertFalse(gtin_check_digit_ok(code))
        # Balance / magasin (2, et UPC 2 ou 4), coupons (5, 98, 99), EAN-8 en 0 ou 2.
        internal = [with_check_digit(body) for body in (
            "200000000001", "21234567890", "41234567890", "51234567890", "980000000001", "990000000001", "2000001",
        )]
        for code in internal:
            with self.subTest(code=code):
                self.assertTrue(is_internal_gtin(code))
        for code in (BAVARIA, NUTELLA, "012345678905", "96385074"):
            with self.subTest(code=code):
                self.assertFalse(is_internal_gtin(code))

    def test_invalid_and_internal_codes_never_reach_the_network(self):
        self.assertEqual(self.info("8714800050846"), {"code": "8714800050846", "status": "invalid", "reason": "checksum"})
        for code in ("PEM12", "12345", " "):
            with self.subTest(code=code):
                self.assertEqual(self.info(code)["reason"], "format")
        self.assertEqual(self.info(with_check_digit("200000000001"))["status"], "internal")
        self.assertEqual(self.network.calls, [])

    def test_quantity_name_and_category_helpers(self):
        self.assertEqual(clean_quantity("400 g e"), "400 g")
        self.assertEqual(clean_quantity("1 L ℮"), "1 L")
        self.assertEqual(clean_quantity(" 500  ml "), "500 ml")
        self.assertEqual(clean_quantity("Coke"), "Coke")
        self.assertEqual(compose_name(InfoProduitExterne(nom="Malt", marque="Bavaria", contenance="500 ml")), "Bavaria Malt 500 ml")
        self.assertEqual(
            compose_name(InfoProduitExterne(nom="Bavaria Malt 0.0% 50cl", marque="Bavaria", contenance="50 cl")),
            "Bavaria Malt 0.0% 50cl",
        )
        self.assertEqual(compose_name(InfoProduitExterne(marque="Bavaria", contenance="500 ml")), "Bavaria 500 ml")

        boissons = Categorie.objects.create(nom="Boissons")
        self.assertEqual(suggest_category(["en:beverages", "en:non-alcoholic-beverages"]), boissons)
        maltees = Categorie.objects.create(nom="Boissons maltées")
        # La plus precise l'emporte.
        self.assertEqual(suggest_category(["en:beverages", "en:malt-beverages"]), maltees)
        Categorie.objects.create(nom="Eaux")
        # Deux candidates aussi precises : pas de suggestion.
        self.assertIsNone(suggest_category(["en:beverages", "en:waters"]))
        self.assertIsNone(suggest_category(["en:frozen-desserts"]))
        self.assertIsNone(suggest_category([]))


class ProductInfoLookupTests(ProductInfoTestCase):
    def test_complete_product_prefills_name_brand_size_photo_and_category(self):
        Categorie.objects.create(nom="Pâtes")
        spreads = Categorie.objects.create(nom="Pâtes à tartiner")
        Categorie.objects.create(nom="Boissons")
        self.route_json(f"{OFF}{NUTELLA}.json", "off_3017620422003.json")

        data = self.info(NUTELLA)

        self.assertEqual(data["status"], "found")
        info = data["info"]
        self.assertEqual((info["nom"], info["marque"], info["contenance"]), ("Nutella", "Nutella", "400 g"))
        self.assertEqual(info["nom_propose"], "Nutella 400 g")
        self.assertEqual(info["image_url"], NUTELLA_IMAGE)
        self.assertTrue(info["photo_enregistrable"])
        self.assertEqual(info["pays"], "France")
        self.assertEqual(info["sources"], [{
            "nom": "Open Food Facts", "licence": "ODbL", "url": f"https://world.openfoodfacts.org/product/{NUTELLA}",
        }])
        self.assertEqual(data["suggested_category"], {"id": spreads.pk, "nom": "Pâtes à tartiner"})
        # Nom et photo trouves : le quota UPCitemdb n'est pas entame.
        self.assertEqual(self.network.urls, [f"{OFF}{NUTELLA}.json"])
        url, kwargs = self.network.calls[0]
        self.assertEqual(kwargs["timeout"], (3, 5))
        self.assertTrue(kwargs["headers"]["User-Agent"].startswith("FacControl-G_Scan/"))
        self.assertIn("product_name_fr", kwargs["params"]["fields"])
        # Jamais de prix ni de donnee fiscale dans la reponse.
        self.assertNotIn("prix", json.dumps(data))
        self.assertNotIn("taxgroup", json.dumps(data))

    def test_partial_product_keeps_the_photo_and_asks_for_the_name(self):
        self.route_json(f"{OFF}{BAVARIA}.json", "off_8714800050845.json")
        self.route_json(UPC, "upcitemdb_empty.json")

        data = self.info(BAVARIA)

        self.assertEqual(data["status"], "partial")
        self.assertEqual(data["info"]["nom"], "")
        self.assertEqual(data["info"]["nom_propose"], "")
        self.assertEqual(data["info"]["image_url"], "https://images.openfoodfacts.org/images/products/871/480/005/0845/front_en.6.400.jpg")
        self.assertEqual(data["info"]["pays"], "Pays-Bas")
        self.assertEqual([source["nom"] for source in data["info"]["sources"]], ["Open Food Facts"])
        self.assertEqual(self.network.urls, [f"{OFF}{BAVARIA}.json", UPC])
        self.assertEqual(self.network.calls[1][1]["params"], {"upc": BAVARIA})
        record = InfoProduitExterne.objects.get(gtin="0" + BAVARIA)
        self.assertTrue(record.trouve)

    def test_upcitemdb_answers_when_open_food_facts_does_not_know_the_code(self):
        self.route_json(f"{OFF}0885909950805.json", "off_not_found.json", status=404)
        self.route_json(UPC, "upcitemdb_885909950805.json")

        data = self.info("885909950805")

        self.assertEqual(data["status"], "found")
        self.assertEqual(data["info"]["nom"], "Apple iPhone 6, Space Gray, 64 GB (T-Mobile)")
        self.assertEqual((data["info"]["marque"], data["info"]["contenance"]), ("Apple", "64GB"))
        # Photos de boutiques : affichees (https seulement) mais jamais enregistrees.
        self.assertTrue(data["info"]["image_url"].startswith("https://i5.walmartimages.com/"))
        self.assertFalse(data["info"]["photo_enregistrable"])
        self.assertEqual(data["info"]["pays"], "États-Unis / Canada")

    def test_failures_fall_through_and_never_cache_a_false_not_found(self):
        self.route(f"{OFF}{BAVARIA}.json", requests.Timeout("lent"))
        self.route(UPC, lambda: response(500, content=b"erreur"))
        self.assertEqual(self.info(BAVARIA)["status"], "unavailable")
        self.assertFalse(InfoProduitExterne.objects.exists())

        self.route(f"{OFF}{BAVARIA}.json", lambda: response(200, content=b"<html>maintenance</html>"))
        self.assertEqual(self.info(BAVARIA)["status"], "unavailable")
        self.assertFalse(InfoProduitExterne.objects.exists())

        # Une base repond, l'autre est en panne : la reponse obtenue suffit.
        self.route_json(f"{OFF}{BAVARIA}.json", "off_8714800050845.json")
        self.assertEqual(self.info(BAVARIA)["status"], "partial")

    def test_rate_limited_upcitemdb_is_paused_for_a_day(self):
        self.route_json(OFF, "off_not_found.json", status=404)
        self.route(UPC, lambda: response(429, payload={"code": "TOO_FAST"}))
        self.assertEqual(self.info(BAVARIA)["status"], "unavailable")
        self.assertEqual(self.network.urls.count(UPC), 1)

        self.assertEqual(self.info(NUTELLA)["status"], "not_found")
        self.assertEqual(self.network.urls.count(UPC), 1)
        status = {provider["nom"]: provider for provider in providers_status()}
        self.assertEqual(status["UPCitemdb"]["raison"], "quota")
        self.assertEqual(status["Go-UPC"]["raison"], "desactive")
        self.set_params(goupc_actif=True)
        self.assertEqual({provider["nom"]: provider for provider in providers_status()}["Go-UPC"]["raison"], "cle")

    def test_cache_avoids_the_network_and_retries_an_expired_not_found(self):
        self.route_json(f"{OFF}{NUTELLA}.json", "off_3017620422003.json")
        self.info(NUTELLA)
        self.info("0" + NUTELLA)
        self.assertEqual(len(self.network.calls), 1)

        self.route_json(f"{OFF}{BAVARIA}.json", "off_not_found.json", status=404)
        self.route_json(UPC, "upcitemdb_empty.json")
        self.assertEqual(self.info(BAVARIA)["status"], "not_found")
        self.assertEqual(self.info(BAVARIA)["status"], "not_found")
        self.assertEqual(len(self.network.calls), 3)
        InfoProduitExterne.objects.filter(gtin="0" + BAVARIA).update(recherche_le=timezone.now() - timedelta(days=8))
        self.route_json(f"{OFF}{BAVARIA}.json", "off_8714800050845.json")
        self.assertEqual(self.info(BAVARIA)["status"], "partial")
        self.assertEqual(len(self.network.calls), 5)

    def test_code_of_an_existing_product_is_reported_without_network(self):
        data = self.info("0012345678905")
        self.assertEqual(data["status"], "exists")
        self.assertEqual(data["existing"], {
            "id": self.product.pk, "nom": "PEMPASE", "url": reverse("facturation:produit-update", args=[self.product.pk]),
        })
        self.assertEqual(self.network.calls, [])

    def test_requires_product_creation_permission_and_is_rate_limited(self):
        agent = get_user_model().objects.create_user(
            username="scan-vendeur", email="vendeur@example.com", role="VENDEUR", point_de_vente=self.pdv,
        )
        UserMenuPermission.objects.create(user=agent, permission_key="produits_create", is_allowed=False)
        self.client.force_login(agent)
        self.assertIn(self.client.get(reverse("gscan:product-info"), {"code": NUTELLA}).status_code, (302, 403))
        self.assertEqual(self.network.calls, [])

        self.client.force_login(self.user)
        self.route_json(f"{OFF}{NUTELLA}.json", "off_3017620422003.json")
        self.set_params(limite_recherches_minute=2)
        self.info(NUTELLA)
        self.info(NUTELLA)
        data = self.info(NUTELLA, expected_status=429)
        self.assertEqual(data["status"], "throttled")
        self.assertIn("patientez une minute", data["error"])

    def test_disabled_lookup_and_paid_provider_with_its_key(self):
        with self.settings(GSCAN_EXTERNAL_LOOKUP=False):
            self.assertEqual(self.info(NUTELLA)["status"], "disabled")
        self.assertEqual(self.network.calls, [])

        self.route_json(OFF, "off_not_found.json", status=404)
        self.route_json(UPC, "upcitemdb_empty.json")
        self.route(GO_UPC, lambda: response(200, {"code": BAVARIA, "product": {
            "name": "Bavaria Malt Original", "brand": "Bavaria", "category": "Soft Drinks",
            "imageUrl": "https://go-upc.s3.amazonaws.com/images/bavaria.jpeg",
        }}))
        # Cle de repli du serveur : le service s'active dans Gestion Scanner.
        with self.settings(GSCAN_GO_UPC_API_KEY="cle-de-test"):
            self.assertEqual(self.info(BAVARIA)["status"], "not_found")
        InfoProduitExterne.objects.all().delete()
        self.set_params(goupc_actif=True)
        with self.settings(GSCAN_GO_UPC_API_KEY="cle-de-test"):
            data = self.info(BAVARIA)
        self.assertEqual(data["status"], "found")
        self.assertEqual(data["info"]["nom_propose"], "Bavaria Malt Original")
        self.assertEqual(self.network.calls[-1][1]["headers"]["Authorization"], "Bearer cle-de-test")


class GoUpcTests(ProductInfoTestCase):
    """Go-UPC selon sa documentation (https://go-upc.com/api) : reponses et erreurs."""

    QUESO = "781138811156"

    def setUp(self):
        super().setUp()
        self.set_params(goupc_actif=True, goupc_cle="cle-go-upc")
        self.route_json(OFF, "off_not_found.json", status=404)
        self.route_json(UPC, "upcitemdb_empty.json")

    def go_upc(self, status=200, payload=None):
        self.route(GO_UPC, lambda: response(status, payload if payload is not None else fixture("goupc_0781138811156.json")))

    def test_documented_answer_prefills_the_product(self):
        Categorie.objects.create(nom="Boissons")
        spreads = Categorie.objects.create(nom="Pâtes à tartiner")
        self.go_upc()

        data = self.info(self.QUESO)

        self.assertEqual(data["status"], "found")
        info = data["info"]
        self.assertEqual(info["nom_propose"], "On the Border Queso, Jalapeno, Spicy - 15.25 Ounce")
        self.assertEqual(info["marque"], "On the Border")
        self.assertEqual(info["image_url"], "https://go-upc.s3.amazonaws.com/images/99132458.jpeg")
        self.assertTrue(info["photo_enregistrable"])
        self.assertEqual(info["pays"], "États-Unis / Canada")
        self.assertEqual(info["sources"], [{"nom": "Go-UPC", "licence": "", "url": "https://go-upc.com/barcode/781138811156"}])
        # Taxonomie Google Shopping : "Dips & Spreads" designe les pates a tartiner.
        self.assertEqual(data["suggested_category"], {"id": spreads.pk, "nom": "Pâtes à tartiner"})
        record = InfoProduitExterne.objects.get(gtin="00" + self.QUESO)
        self.assertEqual(record.categories, ["Food, Beverages & Tobacco", "Food Items", "Dips & Spreads"])
        self.assertEqual(record.brut["Go-UPC"]["codeType"], "UPC")

        # Cle dans l'en-tete Bearer (methode recommandee), jamais dans l'URL.
        go_calls = [(url, kwargs) for url, kwargs in self.network.calls if url.startswith(GO_UPC)]
        self.assertEqual(len(go_calls), 1)
        url, kwargs = go_calls[0]
        self.assertEqual(url, f"{GO_UPC}0{self.QUESO}")
        self.assertEqual(kwargs["headers"]["Authorization"], "Bearer cle-go-upc")
        self.assertIsNone(kwargs["params"])
        self.assertNotIn("cle-go-upc", url)
        # Nom et photo trouves : l'essai UPCitemdb n'est pas entame.
        self.assertNotIn(UPC, self.network.urls)

    def test_size_comes_from_specs(self):
        sample = fixture("goupc_0781138811156.json")
        sample["product"].update(name="Bavaria Malt Apple", brand="Bavaria", specs=[["Organic", "No"], ["Size", "500 ml"]])
        self.go_upc(payload=sample)
        self.assertEqual(self.info(self.QUESO)["info"]["nom_propose"], "Bavaria Malt Apple 500 ml")

    def test_go_upc_completes_a_partial_open_food_facts_answer(self):
        self.route_json(f"{OFF}{BAVARIA}.json", "off_8714800050845.json")
        sample = fixture("goupc_0781138811156.json")
        sample["product"].update(name="Bavaria Smalt Apple 50cl", brand="Bavaria", imageUrl="", specs=[])
        self.go_upc(payload=sample)

        data = self.info(BAVARIA)

        self.assertEqual(data["status"], "found")
        self.assertEqual(data["info"]["nom_propose"], "Bavaria Smalt Apple 50cl")
        # La photo vient d'Open Food Facts, le nom de Go-UPC : UPCitemdb n'est pas appele.
        self.assertTrue(data["info"]["image_url"].startswith("https://images.openfoodfacts.org/"))
        self.assertEqual([source["nom"] for source in data["info"]["sources"]], ["Open Food Facts", "Go-UPC"])
        self.assertEqual(self.network.urls, [f"{OFF}{BAVARIA}.json", f"{GO_UPC}{BAVARIA}"])

    def test_unknown_unrecognised_or_inferred_codes_are_not_used(self):
        cases = {
            "404 inconnu": (404, {"error": "Not found"}),
            "400 format": (400, {"error": "Bad request"}),
            "code devine": (200, {**fixture("goupc_0781138811156.json"), "inferred": True}),
        }
        for label, (status, payload) in cases.items():
            with self.subTest(label):
                InfoProduitExterne.objects.all().delete()
                self.go_upc(status, payload)
                self.assertEqual(self.info(self.QUESO)["status"], "not_found")
        self.assertEqual({provider["nom"]: provider for provider in providers_status()}["Go-UPC"]["raison"], "")

    def test_rejected_key_and_exceeded_quota_pause_the_service(self):
        self.go_upc(401, {"error": "Unauthorized"})
        self.assertEqual(self.info(self.QUESO)["status"], "unavailable")
        self.assertEqual({provider["nom"]: provider for provider in providers_status()}["Go-UPC"]["raison"], "cle_refusee")
        calls = len(self.network.calls)
        self.info(self.QUESO)
        self.assertNotIn(GO_UPC, [url[:len(GO_UPC)] for url in self.network.urls[calls:]])

        # Nouvelle cle : le service reprend (autre code : le premier est en cache).
        self.set_params(goupc_cle="nouvelle-cle")
        self.assertEqual({provider["nom"]: provider for provider in providers_status()}["Go-UPC"]["raison"], "")
        self.go_upc(429, {"error": "Too many requests"})
        self.assertEqual(self.info(BAVARIA)["status"], "unavailable")
        self.assertEqual({provider["nom"]: provider for provider in providers_status()}["Go-UPC"]["raison"], "limite")

    def test_at_most_two_requests_per_second(self):
        provider = GoUpcProvider()
        clock = {"now": 1000.2, "slept": []}

        def sleep(seconds):
            clock["slept"].append(round(seconds, 2))
            clock["now"] += seconds

        with mock.patch("G_Scan.product_info.time.time", lambda: clock["now"]), \
                mock.patch("G_Scan.product_info.time.sleep", sleep):
            for _ in range(3):
                provider.wait_for_rate()
        self.assertEqual(clock["slept"], [0.81])


@override_settings(GSCAN_EXTERNAL_LOOKUP=True)
class ProductPhotoTests(ProductInfoTestCase):
    def setUp(self):
        super().setUp()
        media = tempfile.mkdtemp(prefix="gscan-media-")
        self.addCleanup(shutil.rmtree, media, ignore_errors=True)
        self.enterContext(override_settings(MEDIA_ROOT=media))
        self.record = InfoProduitExterne.objects.create(
            gtin="0" + NUTELLA, nom="Nutella", marque="Nutella", image_url=NUTELLA_IMAGE,
            trouve=True, recherche_le=timezone.now(),
        )

    def photo(self, content=None, kind="image/jpeg", length=None):
        content = jpeg_bytes() if content is None else content
        headers = {"Content-Type": kind, "Content-Length": str(length if length is not None else len(content))}
        self.route(NUTELLA_IMAGE, lambda: response(200, content=content, headers=headers))

    def quick_create(self, **extra):
        data = {
            "nom": "Nutella 400 g", "code_sku": "NUT400", "code_barres": NUTELLA, "prix_vente": "5000",
            "unite_mesure": "U", "typeart": self.kind.pk, "taxgroup": self.group.pk, **extra,
        }
        result = self.client.post(reverse("facturation:pos-quick-product-create"), data)
        self.assertEqual(result.status_code, 200, result.content)
        return Produit.objects.get(code_sku="NUT400")

    def test_quick_creation_downloads_the_requested_photo_from_the_server_cache(self):
        self.photo()
        product = self.quick_create(gscan_use_image="1")
        self.assertTrue(product.image.name.startswith(f"produits/gscan_{NUTELLA}"))
        self.assertEqual(self.network.urls, [NUTELLA_IMAGE])
        kwargs = self.network.calls[0][1]
        self.assertFalse(kwargs["allow_redirects"])
        self.assertTrue(kwargs["stream"])

    def test_product_form_creation_downloads_the_requested_photo(self):
        self.photo()
        result = self.client.post(reverse("facturation:produit-create"), {
            "nom": "Nutella 400 g", "code_sku": "NUT400", "code_barres": NUTELLA, "prix_vente": "5000",
            "unite_mesure": "U", "typeart": self.kind.pk, "taxgroup": self.group.pk, "actif": "on",
            "gscan_use_image": "1",
        })
        self.assertEqual(result.status_code, 302, result.content)
        self.assertTrue(Produit.objects.get(code_sku="NUT400").image.name.startswith(f"produits/gscan_{NUTELLA}"))

    def test_photo_not_requested_is_not_downloaded(self):
        product = self.quick_create()
        self.assertFalse(product.image)
        self.assertEqual(self.network.calls, [])

    def test_user_upload_wins_over_the_public_photo(self):
        self.photo()
        upload = SimpleUploadedFile("ma-photo.jpg", jpeg_bytes(), content_type="image/jpeg")
        product = self.quick_create(gscan_use_image="1", image=upload)
        self.assertIn("ma-photo", product.image.name)
        self.assertEqual(self.network.calls, [])

    def test_untrusted_oversized_or_fake_photos_are_skipped_without_blocking(self):
        product = Produit.objects.create(
            nom="Nutella 400 g", code_sku="NUT400", code_barres=NUTELLA, prix_vente=5000, taxgroup=self.group, typeart=self.kind,
        )
        # Hote hors liste (boutique tierce) : aucune requete.
        self.record.image_url = "https://i5.walmartimages.com/asr/photo.jpeg"
        self.record.save()
        self.assertFalse(attach_external_image(product))
        self.assertEqual(self.network.calls, [])
        self.record.image_url = NUTELLA_IMAGE
        self.record.save()

        cases = {
            "trop lourde (annoncee)": dict(length=3 * 1024 * 1024),
            "trop lourde (reelle)": dict(content=b"\xff" * (2 * 1024 * 1024 + 10), length=0),
            "pas une image": dict(content=b"<html></html>", kind="text/html"),
            "contenu non image": dict(content=b"pas une image", kind="image/jpeg"),
            "format different": dict(kind="image/png"),
        }
        for label, options in cases.items():
            with self.subTest(label):
                self.photo(**options)
                self.assertFalse(attach_external_image(product))
                product.refresh_from_db()
                self.assertFalse(product.image)

        self.route(NUTELLA_IMAGE, requests.ConnectionError("hors ligne"))
        self.assertFalse(attach_external_image(product))


class ProductInfoPagesTests(ProductInfoTestCase):
    def test_creation_form_enables_lookup_but_edition_does_not(self):
        create = self.client.get(reverse("facturation:produit-create"))
        self.assertContains(create, "data-barcode-lookup")
        self.assertContains(create, f'data-lookup-url="{reverse("gscan:product-info")}"')
        self.assertContains(create, "G_Scan/js/gscan-product-info.js")

        update = self.client.get(reverse("facturation:produit-update", args=[self.product.pk]))
        self.assertNotContains(update, "data-barcode-lookup")
        self.assertNotContains(update, "G_Scan/js/gscan-product-info.js")
        self.assertContains(update, "data-barcode-camera")

    def test_pos_add_product_modal_looks_up_scanned_codes(self):
        response = self.client.get(reverse("facturation:pos-view"))
        html = response.content.decode()
        start = html.index('id="quickProductBarcode"')
        field = html[html.rindex("<input", 0, start):html.index(">", start)]
        self.assertIn("data-barcode-lookup", field)
        self.assertIn(f'data-lookup-url="{reverse("gscan:product-info")}"', field)
        self.assertContains(response, "G_Scan/js/gscan-product-info.js")

    def test_scanner_management_shows_providers_cache_and_test_field(self):
        self.user.is_superuser = True
        self.user.save()
        InfoProduitExterne.objects.create(gtin="0" + NUTELLA, nom="Nutella", trouve=True, recherche_le=timezone.now())
        InfoProduitExterne.objects.create(gtin="0" + BAVARIA, trouve=False, recherche_le=timezone.now())
        response = self.client.get(reverse("gscan:scanner-management"))
        self.assertContains(response, "Informations produit publiques")
        self.assertContains(response, "Open Food Facts")
        self.assertContains(response, "Clé API Go-UPC")
        self.assertContains(response, "Désactivée")
        self.assertContains(response, "Cache : 1 fiches trouvées sur 2 codes déjà recherchés.")
        self.assertContains(response, 'id="gscanInfoCode"')
        self.assertContains(response, "G_Scan/js/gscan-product-info.js")

        self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "en"
        english = self.client.get(reverse("gscan:scanner-management"))
        self.assertContains(english, "Public product information")
        self.assertContains(english, "Go-UPC API key")
        self.assertContains(english, "Cache: 1 products found out of 2 barcodes already looked up.")

    def test_english_country_and_throttle_messages(self):
        self.route_json(f"{OFF}{BAVARIA}.json", "off_8714800050845.json")
        self.route_json(UPC, "upcitemdb_empty.json")
        self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "en"
        self.assertEqual(self.info(BAVARIA)["info"]["pays"], "Netherlands")
        self.set_params(limite_recherches_minute=0)
        self.assertIn("wait a minute", self.info(BAVARIA, expected_status=429)["error"])
