"""Vérification des images SneakSafe chargées sur la page produit"""

import json
import time
import subprocess
import sys

# Lancer Chrome en mode CDP
chrome_cmd = [
    r"C:\Program Files\Google\Chrome\Application\chrome.exe",
    "--remote-debugging-port=9222",
    "--user-data-dir=C:\\Users\\lisa\\.playwright-mcp\\chrome-data",
    "https://www.ysenra.fr/products/sneaksafe-sac-lavage-chaussures"
]

print("Lancement de Chrome...")
proc = subprocess.Popen(chrome_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

time.sleep(5)

try:
    import requests

    # Connexion CDP
    ws_url_resp = requests.get("http://localhost:9222/json")
    targets = ws_url_resp.json()

    # Trouver la page SneakSafe
    for target in targets:
        if 'sneaksafe' in target.get('url', '').lower():
            print(f"✓ Page trouvée : {target['url']}")

            # Récupérer le contenu
            import websocket
            ws = websocket.create_connection(target['webSocketDebuggerUrl'])

            # Activer DOM
            ws.send(json.dumps({"id": 1, "method": "DOM.enable"}))
            ws.recv()

            # Récupérer le document
            ws.send(json.dumps({"id": 2, "method": "DOM.getDocument"}))
            result = json.loads(ws.recv())

            # Chercher les images
            ws.send(json.dumps({
                "id": 3,
                "method": "DOM.querySelectorAll",
                "params": {
                    "nodeId": result['result']['root']['nodeId'],
                    "selector": "img[src*='sneaksafe'], img[data-src*='sneaksafe']"
                }
            }))
            result = json.loads(ws.recv())

            print(f"\nImages SneakSafe trouvées : {len(result['result']['nodeIds'])}")
            print("=" * 70)

            for node_id in result['result']['nodeIds'][:10]:  # Limiter à 10
                ws.send(json.dumps({
                    "id": node_id + 100,
                    "method": "DOM.getAttributes",
                    "params": {"nodeId": node_id}
                }))
                attrs_result = json.loads(ws.recv())
                attrs = attrs_result['result']['attributes']

                # Extraire src ou data-src
                attrs_dict = dict(zip(attrs[::2], attrs[1::2]))
                src = attrs_dict.get('src') or attrs_dict.get('data-src', '')

                if src:
                    filename = src.split('/')[-1].split('?')[0]
                    print(f"  • {filename}")

                    if 'packshot' in filename or 'vrai' in filename:
                        print(f"    ✓ VRAIE PHOTO")
                    elif 'hero-studio' in filename or 'chenille-360' in filename:
                        print(f"    ✗ RENDU CGI (PROBLÈME !)")

            ws.close()
            break

except Exception as e:
    print(f"Erreur : {e}")
    import traceback
    traceback.print_exc()
finally:
    # Fermer Chrome
    proc.terminate()
