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:
        # Wait for any rich text that includes calorie/macro info
        time.sleep(10)
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '[data-testid="richTextElement"]'))
        )
        print("✅ Page content loaded.")
    except:
        print("⚠️ Timed out waiting for content.")

    time.sleep(1.5)  # Give JS more time to finish rendering

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

    # Each item seems to be wrapped in a <div role="listitem">
    for div in soup.find_all("div", {"role": "listitem"}):
        try:
            # Name: search for the first <p> inside a collapsible text
            name_tag = div.find("div", class_="wixui-collapsible-text")
            name = name_tag.get_text(strip=True) if name_tag else "N/A"

            # Macros / Description: look for another collapsible text block
            details = ""
            for detail_div in div.find_all("div", class_="wixui-collapsible-text"):
                txt = detail_div.get_text(strip=True)
                if txt != name:
                    details = txt
                    break

            # Price: look for a <p> containing a dollar sign
            price_tag = div.find("p", string=lambda s: s and "$" in s)
            price = price_tag.get_text(strip=True) if price_tag else "N/A"

            # Image URL: look for the <img> tag
            img_tag = div.find("img")
            img_url = img_tag["src"] if img_tag else "N/A"

            items.append({
                "name": name,
                "details": details,
                "price": price,
                "image": img_url
            })

        except Exception as e:
            print(f"⚠️ Skipping item due to error: {e}")
            continue

    return items