"""
Tests d'intégration pour le registry avec les stores réels.

Teste la détection automatique du bon store pour des URLs
Amazon, Cdiscount, Backmarket et AliExpress.
"""

import pytest

from pricewatch.app.core.registry import StoreRegistry
from pricewatch.app.stores.amazon.store import AmazonStore
from pricewatch.app.stores.cdiscount.store import CdiscountStore
from pricewatch.app.stores.backmarket.store import BackmarketStore
from pricewatch.app.stores.aliexpress.store import AliexpressStore


class TestRegistryRealStores:
    """Tests d'intégration avec les 4 stores réels."""

    @pytest.fixture
    def registry_with_all_stores(self) -> StoreRegistry:
        """Fixture: Registry avec les 4 stores réels enregistrés."""
        registry = StoreRegistry()
        registry.register(AmazonStore())
        registry.register(CdiscountStore())
        registry.register(BackmarketStore())
        registry.register(AliexpressStore())
        return registry

    def test_all_stores_registered(self, registry_with_all_stores):
        """Vérifie que les 4 stores sont enregistrés."""
        assert len(registry_with_all_stores) == 4
        stores = registry_with_all_stores.list_stores()
        assert "amazon" in stores
        assert "cdiscount" in stores
        assert "backmarket" in stores
        assert "aliexpress" in stores

    def test_detect_amazon_fr(self, registry_with_all_stores):
        """Détecte Amazon.fr correctement."""
        url = "https://www.amazon.fr/dp/B08N5WRWNW"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "amazon"

    def test_detect_amazon_com(self, registry_with_all_stores):
        """Détecte Amazon.com correctement."""
        url = "https://www.amazon.com/dp/B08N5WRWNW"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "amazon"

    def test_detect_amazon_with_product_name(self, registry_with_all_stores):
        """Détecte Amazon avec nom de produit dans l'URL."""
        url = "https://www.amazon.fr/Product-Name-Here/dp/B08N5WRWNW/ref=sr_1_1"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "amazon"

    def test_detect_cdiscount(self, registry_with_all_stores):
        """Détecte Cdiscount correctement."""
        url = "https://www.cdiscount.com/informatique/clavier-souris-webcam/example/f-1070123-example.html"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "cdiscount"

    def test_detect_backmarket(self, registry_with_all_stores):
        """Détecte Backmarket correctement."""
        url = "https://www.backmarket.fr/fr-fr/p/iphone-15-pro"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "backmarket"

    def test_detect_backmarket_locale_en(self, registry_with_all_stores):
        """Détecte Backmarket avec locale anglais."""
        url = "https://www.backmarket.fr/en-fr/p/macbook-air-15-2024"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "backmarket"

    def test_detect_aliexpress_fr(self, registry_with_all_stores):
        """Détecte AliExpress.fr correctement."""
        url = "https://fr.aliexpress.com/item/1005007187023722.html"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "aliexpress"

    def test_detect_aliexpress_com(self, registry_with_all_stores):
        """Détecte AliExpress.com correctement."""
        url = "https://www.aliexpress.com/item/1005007187023722.html"
        store = registry_with_all_stores.detect_store(url)
        assert store is not None
        assert store.store_id == "aliexpress"

    def test_detect_unknown_store(self, registry_with_all_stores):
        """URL inconnue retourne None."""
        url = "https://www.ebay.com/itm/123456789"
        store = registry_with_all_stores.detect_store(url)
        assert store is None

    def test_detect_invalid_url(self, registry_with_all_stores):
        """URL invalide retourne None."""
        url = "not-a-valid-url"
        store = registry_with_all_stores.detect_store(url)
        assert store is None

    def test_detect_priority_amazon_over_others(self, registry_with_all_stores):
        """Amazon.fr doit avoir le meilleur score pour ses URLs."""
        url = "https://www.amazon.fr/dp/B08N5WRWNW"
        store = registry_with_all_stores.detect_store(url)
        # Amazon.fr devrait avoir score 0.9, les autres 0.0
        assert store.store_id == "amazon"

    def test_each_store_matches_only_own_urls(self, registry_with_all_stores):
        """Chaque store ne matche que ses propres URLs."""
        test_cases = [
            ("https://www.amazon.fr/dp/B08N5WRWNW", "amazon"),
            ("https://www.cdiscount.com/product", "cdiscount"),
            ("https://www.backmarket.fr/fr-fr/p/product", "backmarket"),
            ("https://fr.aliexpress.com/item/12345.html", "aliexpress"),
        ]

        for url, expected_store_id in test_cases:
            store = registry_with_all_stores.detect_store(url)
            assert store is not None, f"Aucun store détecté pour {url}"
            assert store.store_id == expected_store_id, (
                f"Mauvais store pour {url}: "
                f"attendu {expected_store_id}, obtenu {store.store_id}"
            )

    def test_get_store_by_id(self, registry_with_all_stores):
        """Récupère chaque store par son ID."""
        amazon = registry_with_all_stores.get_store("amazon")
        assert amazon is not None
        assert isinstance(amazon, AmazonStore)

        cdiscount = registry_with_all_stores.get_store("cdiscount")
        assert cdiscount is not None
        assert isinstance(cdiscount, CdiscountStore)

        backmarket = registry_with_all_stores.get_store("backmarket")
        assert backmarket is not None
        assert isinstance(backmarket, BackmarketStore)

        aliexpress = registry_with_all_stores.get_store("aliexpress")
        assert aliexpress is not None
        assert isinstance(aliexpress, AliexpressStore)

    def test_unregister_store(self, registry_with_all_stores):
        """Désenregistre un store et vérifie qu'il n'est plus détecté."""
        assert len(registry_with_all_stores) == 4

        # Désenregistrer Amazon
        removed = registry_with_all_stores.unregister("amazon")
        assert removed is True
        assert len(registry_with_all_stores) == 3

        # Amazon ne doit plus être détecté
        store = registry_with_all_stores.detect_store("https://www.amazon.fr/dp/B08N5WRWNW")
        assert store is None

        # Les autres stores doivent toujours fonctionner
        store = registry_with_all_stores.detect_store("https://www.cdiscount.com/product")
        assert store is not None
        assert store.store_id == "cdiscount"

    def test_repr_includes_all_stores(self, registry_with_all_stores):
        """La représentation string inclut tous les stores."""
        repr_str = repr(registry_with_all_stores)
        assert "StoreRegistry" in repr_str
        assert "amazon" in repr_str
        assert "cdiscount" in repr_str
        assert "backmarket" in repr_str
        assert "aliexpress" in repr_str
