#!/usr/bin/env python3
import json
import sys
from selenium import webdriver
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
import time

input_file = sys.argv[1] if len(sys.argv) > 1 else None
if not input_file:
    print(json.dumps({"success": False, "error": "Arquivo de entrada não fornecido"}))
    sys.exit(1)

with open(input_file, 'r', encoding='utf-8') as f:
    data = json.load(f)

try:
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
    
    driver = webdriver.Chrome(options=chrome_options)
    
    # Construir URL
    params = {'searchTerm': data['termo'], 'lang': 'pt_BR'}
    if data.get('modelo'):
        params['model'] = data['modelo']
    if data.get('ano'):
        params['year'] = data['ano']
    
    url = data['url'] + 'index.html?' + '&'.join([f"{k}={v}" for k, v in params.items()])
    driver.get(url)
    
    # Aguardar carregamento
    time.sleep(3)
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
    
    # Extrair dados
    pecas = []
    items = driver.find_elements(By.CSS_SELECTOR, '.part-item, tr.part-row, [data-part-code]')
    
    for item in items:
        try:
            codigo_elem = item.find_element(By.CSS_SELECTOR, '.part-code, [data-part-code], td:first-child')
            nome_elem = item.find_element(By.CSS_SELECTOR, '.part-name, [data-part-name], td:nth-child(2)')
            
            codigo = codigo_elem.text.strip()
            nome = nome_elem.text.strip()
            
            if codigo and nome:
                preco = None
                try:
                    preco_elem = item.find_element(By.CSS_SELECTOR, '.price, [data-price], td:nth-child(3)')
                    preco_str = preco_elem.text.strip()
                    preco = float(preco_str.replace(',', '.').replace('R$', '').strip())
                except:
                    pass
                
                pecas.append({
                    'codigo_yamaha': codigo,
                    'nome': nome,
                    'preco_yamaha': preco,
                    'status': 'disponivel'
                })
        except:
            continue
    
    driver.quit()
    print(json.dumps({"success": True, "data": pecas}))
    
except Exception as e:
    print(json.dumps({"success": False, "error": str(e)}))
    sys.exit(1)

