#!/usr/bin/env python3
"""
Wildberries Product Data Fetcher with Selenium
Handles anti-bot protection automatically
"""

import json
import re
import time
from typing import Dict, Optional

def fetch_wb_product_selenium(url: str, headless: bool = True) -> Optional[Dict]:
    """
    Fetch Wildberries product data using Selenium

    Args:
        url: WB product URL
        headless: Run browser in headless mode

    Returns:
        Product data dict with name, images, price, description
    """
    try:
        from selenium import webdriver
        from selenium.webdriver.chrome.service import Service
        from selenium.webdriver.chrome.options import Options
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC
        from webdriver_manager.chrome import ChromeDriverManager
    except ImportError:
        print("Selenium not installed. Install with: pip install selenium webdriver-manager")
        return None

    # Setup Chrome options
    chrome_options = Options()

    # Use system chromium
    chrome_options.binary_location = '/usr/bin/chromium-browser'

    if headless:
        chrome_options.add_argument('--headless=new')
    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_argument('--disable-gpu')
    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')

    # Exclude automation flags
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)

    try:
        print(f"Launching browser...")
        # Use webdriver-manager to automatically download and manage chromedriver
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=chrome_options)

        # Navigate to product page
        print(f"Fetching: {url}")
        driver.get(url)

        # Wait for anti-bot check to complete
        print("Waiting for page to load (anti-bot check)...")
        time.sleep(5)  # Give time for anti-bot to resolve

        # Wait for product title to appear
        try:
            WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, '.product-page__title, h1'))
            )
            print("✓ Page loaded successfully")
        except:
            print("⚠ Timeout waiting for product title, trying anyway...")

        # Extract product data using JavaScript
        product_data = driver.execute_script("""
            // Product name
            const nameEl = document.querySelector('.product-page__title, h1');
            const name = nameEl ? nameEl.textContent.trim() : '';

            // Images - get all high-res versions
            const images = [];
            const imageElements = document.querySelectorAll('.photo-zoom__preview img, .swiper-wrapper img, [class*="photo"] img, [class*="image"] img');

            imageElements.forEach(img => {
                let src = img.src || img.getAttribute('data-src') || img.getAttribute('data-link');
                if (src && src.includes('basket') && !images.includes(src)) {
                    // Convert to big/high-res version
                    src = src.replace('/tm/', '/big/')
                             .replace('/c246x328/', '/')
                             .replace('/c516x688/', '/')
                             .replace('/c1200x1200/', '/');
                    images.push(src);
                }
            });

            // Price
            const priceEl = document.querySelector('.price-block__final-price, [class*="price"]');
            const price = priceEl ? priceEl.textContent.trim() : '';

            // Brand
            const brandEl = document.querySelector('.product-page__header-brand, [class*="brand"]');
            const brand = brandEl ? brandEl.textContent.trim() : '';

            // Description
            const descEl = document.querySelector('.product-page__description-text, [class*="description"]');
            const description = descEl ? descEl.textContent.trim() : '';

            // Characteristics
            const characteristics = {};
            const charElements = document.querySelectorAll('.product-params__table tr, .product-params__row');
            charElements.forEach(row => {
                const key = row.querySelector('th, .product-params__cell:first-child');
                const value = row.querySelector('td, .product-params__cell:last-child');
                if (key && value) {
                    characteristics[key.textContent.trim()] = value.textContent.trim();
                }
            });

            return {
                name,
                brand,
                images,
                price,
                description,
                characteristics
            };
        """)

        # Extract product ID from URL
        match = re.search(r'/catalog/(\d+)/', url)
        if match:
            product_data['product_id'] = match.group(1)

        product_data['url'] = url

        # Determine product type
        name_lower = product_data.get('name', '').lower()
        product_type = 'general'

        if any(word in name_lower for word in ['сковород', 'кастрюл', 'посуд', 'тарелк']):
            product_type = 'kitchenware'
        elif any(word in name_lower for word in ['платье', 'футболк', 'брюк', 'куртк', 'свитер', 'одежд']):
            product_type = 'fashion'
        elif any(word in name_lower for word in ['наушник', 'телефон', 'ноутбук', 'планшет', 'часы']):
            product_type = 'electronics'
        elif any(word in name_lower for word in ['стул', 'стол', 'шкаф', 'диван', 'кресло']):
            product_type = 'furniture'
        elif any(word in name_lower for word in ['крем', 'шампунь', 'косметик', 'сыворотк', 'маск']):
            product_type = 'beauty'
        elif any(word in name_lower for word in ['чай', 'кофе', 'печенье', 'шоколад', 'конфет']):
            product_type = 'food'

        product_data['type'] = product_type

        # Close browser
        driver.quit()

        return product_data

    except Exception as e:
        print(f"Error fetching product: {e}")
        try:
            driver.quit()
        except:
            pass
        return None


if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("Usage: python wb_fetcher_selenium.py <WB_URL>")
        sys.exit(1)

    url = sys.argv[1]
    data = fetch_wb_product_selenium(url, headless=True)

    if data:
        print("\n=== Product Data ===")
        print(json.dumps(data, indent=2, ensure_ascii=False))

        # Save to file
        if data.get('product_id'):
            filename = f"product_{data['product_id']}.json"
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2, ensure_ascii=False)
            print(f"\n✓ Saved to: {filename}")
    else:
        print("Failed to fetch product data")
