import threading
import time
import psycopg2
from datetime import datetime

def check_database():
    """Проверка состояния базы данных"""
    db_config = {
        'host': '127.0.0.1',
        'database': 'aliexpress_automation',
        'user': 'automation_user',
        'password': 'AutoPass123'
    }
    
    try:
        conn = psycopg2.connect(**db_config)
        cursor = conn.cursor()
        
        # Общее количество товаров
        cursor.execute("SELECT COUNT(*) FROM products")
        total = cursor.fetchone()[0]
        
        # Активные товары
        cursor.execute("SELECT COUNT(*) FROM products WHERE status = 'active'")
        active = cursor.fetchone()[0]
        
        # Товары добавленные сегодня
        cursor.execute("SELECT COUNT(*) FROM products WHERE created_at::date = CURRENT_DATE")
        today = cursor.fetchone()[0]
        
        # Последние 5 товаров
        cursor.execute("""
            SELECT id, title, created_at 
            FROM products 
            ORDER BY created_at DESC 
            LIMIT 5
        """)
        recent = cursor.fetchall()
        
        print(f"📊 Статистика базы данных:")
        print(f"   Всего товаров: {total}")
        print(f"   Активных: {active}")
        print(f"   Добавлено сегодня: {today}")
        print(f"\n📝 Последние товары:")
        for item in recent:
            print(f"   ID: {item[0]}, {item[1][:50]}..., {item[2]}")
        
        cursor.close()
        conn.close()
        
    except Exception as e:
        print(f"❌ Ошибка проверки БД: {e}")

def simulate_parser_thread():
    """Симуляция работы парсера в отдельном потоке"""
    print("🔄 Запуск симуляции парсера в отдельном потоке...")
    
    def parser_work():
        print("🚀 Парсер начал работу в потоке:", threading.current_thread().name)
        
        # Симулируем работу парсера
        for i in range(3):
            print(f"⏳ Парсер работает... {i+1}/3")
            time.sleep(2)
        
        # Добавляем тестовый товар
        try:
            from simple_parser import SimpleAliExpressParser
            parser = SimpleAliExpressParser()
            
            test_product = {
                'title': f'Тестовый товар из потока {int(time.time())}',
                'price': 999.99,
                'original_price': 1499.99,
                'main_image': 'https://example.com/test.jpg',
                'aliexpress_link': f'https://aliexpress.com/item/thread{int(time.time())}.html',
                'rating': 4.0,
                'orders_count': 50,
                'original_description': 'Товар добавлен из тестового потока',
                'category': 'other'
            }
            
            # Добавляем в БД
            conn = psycopg2.connect(**parser.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}")
            
        except Exception as e:
            print(f"❌ Ошибка в потоке парсера: {e}")
        
        print("🏁 Парсер завершил работу в потоке")
    
    # Запускаем в отдельном потоке
    thread = threading.Thread(target=parser_work, name="ParserThread")
    thread.start()
    
    print("⏰ Ожидание завершения потока...")
    thread.join()
    print("✅ Поток завершен")

def main():
    print("🔍 Отладка парсера AliExpress")
    print("=" * 50)
    
    # 1. Проверяем БД до
    print("\n1️⃣ Состояние БД ДО тестирования:")
    check_database()
    
    # 2. Запускаем симуляцию парсера
    print("\n2️⃣ Тестирование работы в потоке:")
    simulate_parser_thread()
    
    # 3. Проверяем БД после
    print("\n3️⃣ Состояние БД ПОСЛЕ тестирования:")
    check_database()

if __name__ == "__main__":
    main()
