#!/usr/bin/env python3
"""
Test script to verify Tokopedia access
"""

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
import time

def test_tokopedia_access():
    """Test accessing Tokopedia"""
    print("Initializing Chrome WebDriver...")
    
    # Set up Chrome options
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    
    try:
        # Initialize the driver
        print("Creating WebDriver instance...")
        driver = webdriver.Chrome(options=chrome_options)
        
        print("WebDriver created successfully!")
        print("Loading Tokopedia homepage...")
        
        # Load Tokopedia homepage
        driver.get("https://www.tokopedia.com")
        print(f"Page title: {driver.title}")
        
        # Wait for page to load
        time.sleep(5)
        
        print("Loading search results...")
        # Try searching for a simple term
        search_url = "https://www.tokopedia.com/search?st=product&q=phone"
        driver.get(search_url)
        
        # Wait for search results to load
        print("Waiting for search results...")
        WebDriverWait(driver, 30).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "[data-testid='divProductWrapper']"))
        )
        
        print("Search results loaded successfully!")
        
        # Find product elements
        product_elements = driver.find_elements(By.CSS_SELECTOR, "[data-testid='divProductWrapper']")
        print(f"Found {len(product_elements)} product elements")
        
        if product_elements:
            # Try to extract info from first product
            first_product = product_elements[0]
            try:
                name_element = first_product.find_element(By.CSS_SELECTOR, "[data-testid='spnSRPProdName']")
                print(f"First product name: {name_element.text[:50]}...")
            except Exception as e:
                print(f"Could not extract product name: {e}")
        
        driver.quit()
        return True
        
    except TimeoutException:
        print("Timeout while waiting for elements")
        driver.quit()
        return False
    except Exception as e:
        print(f"Error: {e}")
        driver.quit()
        return False

if __name__ == "__main__":
    success = test_tokopedia_access()
    if success:
        print("\nTokopedia access test completed successfully!")
    else:
        print("\nTokopedia access test failed!")