import time
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def scrape(driver, url):
    driver.get(url)

    try:
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '[data-elementor-type="loop-item"]'))
        )
        print("✅ Page content loaded.")
    except:
        print("⚠️ Timed out waiting for product elements.")

    time.sleep(1.5)

    soup = BeautifulSoup(driver.page_source, 'html.parser')
    items = []

    product_cards = soup.select('[data-elementor-type="loop-item"]')

    for card in product_cards:
        name_el = card.select_one('h1.product_title a')
        price_el = card.select_one('p.price span.woocommerce-Price-amount bdi')
        img_el = card.select_one('.elementor-widget-theme-post-featured-image img')

        if not name_el or not price_el or not img_el:
            continue

        items.append({
            "name": name_el.get_text(strip=True),
            "price": price_el.get_text(strip=True),
            "url": name_el.get("href"),
            "image": img_el.get("src")
        })

    return items