import os
import time
from bs4 import BeautifulSoup
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


def _setup_driver():
    USER_DATA_DIR = os.path.join(os.getcwd(), "chrome-user-data")
    chrome_options = Options()
    chrome_options.add_argument(f"--user-data-dir={USER_DATA_DIR}")
    chrome_options.add_argument("--profile-directory=Default")
    chrome_options.add_argument("--start-maximized")
    driver = webdriver.Chrome(options=chrome_options)
    return driver


def get_amazon_product_details(asin):
    """Returns product details for a single ASIN."""
    driver = _setup_driver()
    try:
        return _scrape_product_details(driver, asin)
    finally:
        driver.quit()


def get_multiple_product_details(asin_list, delay=5):
    """Returns product details for a list of ASINs."""
    driver = _setup_driver()
    results = []
    try:
        for asin in asin_list:
            try:
                data = _scrape_product_details(driver, asin)
                results.append(data)
                print(f"Scraped: {asin}")
            except Exception as e:
                print(f"Failed {asin}: {e}")
                results.append({'ASIN': asin, 'Error': str(e)})
            time.sleep(delay)
    finally:
        driver.quit()
    return results


def _scrape_product_details(driver, asin):
    url = f"https://www.amazon.in/dp/{asin}"
    driver.get(url)
    WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
    soup = BeautifulSoup(driver.page_source, 'html.parser')

    def safe_find(selector, attr=None):
        tag = soup.select_one(selector)
        if tag:
            return tag.get(attr) if attr else tag.get_text(strip=True)
        return 'N/A'

    title = safe_find('#productTitle')

    # Updated price extraction
    price_tag = soup.select_one('.a-price .a-offscreen')
    price = price_tag.get_text(strip=True) if price_tag else 'N/A'

    # Updated rating extraction
    rating_tag = soup.select_one('#acrPopover')
    rating = rating_tag['title'] if rating_tag and 'title' in rating_tag.attrs else 'N/A'

    reviews = safe_find('#acrCustomerReviewText')
    image = safe_find('#landingImage', 'src')

    if reviews != 'N/A':
        reviews = ''.join(filter(str.isdigit, reviews))

    return {
        'ASIN': asin,
        'Title': title,
        'Price': price,
        'Rating': rating,
        'Reviews': reviews,
        'Image': image,
    }