import time
import json
import re
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import psycopg2
from datetime import datetime

class TestAliExpressParser:
    def __init__(self):
        self.setup_driver()
        self.db_config = {
            'host': '127.0.0.1',
            'database': 'aliexpress_automation',
            'user': 'automation_user',
            'password': 'AutoPass123'
        }
    
    def setup_driver(self):
        """Настройка веб-драйвера с отладкой"""
        print("🔧 Настройка веб-драйвера...")
        chrome_options = Options()
        # Убираем headless для отладки
        # chrome_options.add_argument('--headless')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-dev-shm-usage')
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
        
        try:
            service = Service(ChromeDriverManager().install())
            self.driver = webdriver.Chrome(service=service, options=chrome_options)
            self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
            print("✅ Веб-драйвер успешно инициализирован")
        except Exception as e:
            print(f"❌ Ошибка инициализации веб-драйвера: {e}")
            raise
    
    def test_database_connection(self):
        """Тест подключения к базе данных"""
        print("\n🔗 Тестирование подключения к базе данных...")
        try:
            conn = psycopg2.connect(**self.db_config)
            cursor = conn.cursor()
            cursor.execute("SELECT COUNT(*) FROM products")
            count = cursor.fetchone()[0]
            print(f"✅ Подключение к БД успешно. Товаров в базе: {count}")
            cursor.close()
            conn.close()
            return True
        except Exception as e:
            print(f"❌ Ошибка подключения к БД: {e}")
            return False
    
    def test_simple_page_load(self):
        """Тест загрузки простой страницы"""
        print("\n🌐 Тестирование загрузки страницы...")
        try:
            # Сначала тестируем простую страницу
            self.driver.get("https://httpbin.org/user-agent")
            time.sleep(2)
            print(f"✅ Страница загружена. User-Agent: {self.driver.find_element(By.TAG_NAME, 'body').text}")
            
            # Теперь пробуем AliExpress
            print("🔍 Загрузка главной страницы AliExpress...")
            self.driver.get("https://www.aliexpress.com")
            time.sleep(5)
            
            title = self.driver.title
            print(f"✅ AliExpress загружен. Заголовок: {title}")
            return True
        except Exception as e:
            print(f"❌ Ошибка загрузки страницы: {e}")
            return False
    
    def test_search_page(self, query="camping"):
        """Тест страницы поиска"""
        print(f"\n🔍 Тестирование поиска: '{query}'...")
        try:
            search_url = f"https://www.aliexpress.com/wholesale?SearchText={query}"
            print(f"Переход на: {search_url}")
            
            self.driver.get(search_url)
            time.sleep(10)  # Увеличиваем время ожидания
            
            print(f"Текущий URL: {self.driver.current_url}")
            print(f"Заголовок страницы: {self.driver.title}")
            
            # Проверяем, есть ли товары на странице
            product_selectors = [
                "a[href*='/item/']",
                "[data-widget-cid*='product']",
                ".list-item",
                ".product-item",
                "[class*='item']"
            ]
            
            found_products = []
            for selector in product_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        print(f"✅ Найдено {len(elements)} элементов по селектору: {selector}")
                        found_products.extend(elements[:5])  # Берем первые 5
                        break
                except:
                    continue
            
            if found_products:
                print("🎯 Найденные ссылки на товары:")
                for i, element in enumerate(found_products[:3]):
                    try:
                        href = element.get_attribute('href')
                        if href and '/item/' in href:
                            print(f"  {i+1}. {href}")
                    except:
                        continue
                return True
            else:
                print("❌ Товары не найдены. Возможно, AliExpress заблокировал доступ.")
                # Сохраним скриншот для отладки
                self.driver.save_screenshot("debug_search_page.png")
                print("📸 Скриншот сохранен как debug_search_page.png")
                return False
                
        except Exception as e:
            print(f"❌ Ошибка при тестировании поиска: {e}")
            return False
    
    def test_product_page_parsing(self):
        """Тест парсинга конкретной страницы товара"""
        print("\n📦 Тестирование парсинга страницы товара...")
        
        # Используем тестовую ссылку
        test_url = "https://www.aliexpress.com/item/1005004792604923.html"
        
        try:
            print(f"Переход на: {test_url}")
            self.driver.get(test_url)
            time.sleep(10)
            
            print(f"Текущий URL: {self.driver.current_url}")
            print(f"Заголовок страницы: {self.driver.title}")
            
            # Пробуем разные селекторы для названия
            title_selectors = [
                "h1",
                "[data-pl='product-title']",
                ".product-title",
                "[class*='title']"
            ]
            
            title = "Название не найдено"
            for selector in title_selectors:
                try:
                    element = self.driver.find_element(By.CSS_SELECTOR, selector)
                    if element.text.strip():
                        title = element.text.strip()
                        print(f"✅ Название найдено по селектору {selector}: {title[:100]}...")
                        break
                except:
                    continue
            
            # Пробуем найти цену
            price_selectors = [
                "[class*='price']",
                "[data-spm-anchor-id*='price']",
                ".price-current",
                ".notranslate"
            ]
            
            price = "Цена не найдена"
            for selector in price_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        text = element.text.strip()
                        if text and ('$' in text or '₽' in text or re.search(r'\d+', text)):
                            price = text
                            print(f"✅ Цена найдена: {price}")
                            break
                    if price != "Цена не найдена":
                        break
                except:
                    continue
            
            # Сохраним скриншот
            self.driver.save_screenshot("debug_product_page.png")
            print("📸 Скриншот сохранен как debug_product_page.png")
            
            return {
                'title': title,
                'price': price,
                'url': test_url
            }
            
        except Exception as e:
            print(f"❌ Ошибка при парсинге товара: {e}")
            return None
    
    def test_save_product(self):
        """Тест сохранения тестового товара в БД"""
        print("\n💾 Тестирование сохранения товара в БД...")
        
        test_product = {
            'title': 'Тестовый товар для кемпера',
            'price': 100.50,
            'original_price': 150.00,
            'main_image': 'https://example.com/test.jpg',
            'aliexpress_link': f'https://aliexpress.com/item/test{int(time.time())}.html',
            'rating': 4.5,
            'orders_count': 100,
            'original_description': 'Тестовое описание товара',
            'category': 'electronics'
        }
        
        try:
            conn = psycopg2.connect(**self.db_config)
            cursor = conn.cursor()
            
            insert_query = """
                INSERT INTO products (
                    title, original_description, price, original_price,
                    main_image, category, aliexpress_link, rating, orders_count,
                    status, created_at, updated_at
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                RETURNING id
            """
            
            cursor.execute(insert_query, (
                test_product['title'],
                test_product['original_description'],
                test_product['price'],
                test_product['original_price'],
                test_product['main_image'],
                test_product['category'],
                test_product['aliexpress_link'],
                test_product['rating'],
                test_product['orders_count'],
                'active',
                datetime.now(),
                datetime.now()
            ))
            
            product_id = cursor.fetchone()[0]
            conn.commit()
            cursor.close()
            conn.close()
            
            print(f"✅ Тестовый товар успешно добавлен с ID: {product_id}")
            return True
            
        except Exception as e:
            print(f"❌ Ошибка при сохранении товара: {e}")
            return False
    
    def run_full_test(self):
        """Запуск полного теста"""
        print("🚀 Запуск полного теста парсера AliExpress...")
        print("=" * 60)
        
        # 1. Тест БД
        if not self.test_database_connection():
            return False
        
        # 2. Тест загрузки страниц
        if not self.test_simple_page_load():
            return False
        
        # 3. Тест поиска
        if not self.test_search_page():
            print("⚠️ Поиск не работает, но продолжаем тестирование...")
        
        # 4. Тест парсинга товара
        product_data = self.test_product_page_parsing()
        if product_data:
            print(f"✅ Парсинг товара работает: {product_data}")
        
        # 5. Тест сохранения в БД
        if not self.test_save_product():
            return False
        
        print("\n" + "=" * 60)
        print<span class="cursor">█</span>