import sys
import os
import logging
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
from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException
from selenium.webdriver.common.action_chains import ActionChains

# ----------------- CONFIG -------------------
SHOW_LOGS = False
MAX_RETRIES = 2
WAIT_TIME = 20
LOGIN_WAIT_TIME = 10
LOG_FILE = '/home/auto11/public_html/scripts/pilkington_scraper.log'
# -------------------------------------------

# Set up logging
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    handlers=[
        logging.FileHandler(LOG_FILE),
        logging.StreamHandler() if SHOW_LOGS else logging.NullHandler()
    ]
)
logger = logging.getLogger(__name__)

# Setup Chrome options
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--headless")  # Comment out for debugging

# Set a consistent viewport size
chrome_options.add_argument("--window-size=1920,1080")

# Initialize WebDriver
driver = webdriver.Chrome(options=chrome_options)

# Retrieve part number from command-line arguments
partNo = sys.argv[1]

# Retrieve credentials from environment variables or use defaults
USERNAME = "beau"
PASSWORD = "beauqwerty123456"

try:
    # Navigate to the search page
    driver.get(f"https://shop.pilkington.com/ecomm/search/advanced/?queryType=2&query={partNo}&inRange=1&page=1&pageSize=30&sort=PopularityRankAsc")
    # logger.info("Website loaded.")

    # Wait for login form to be present
    WebDriverWait(driver, LOGIN_WAIT_TIME).until(EC.presence_of_element_located((By.TAG_NAME, "form")))
    # logger.info("Login page detected.")

    # Locate username and password fields
    username_field = WebDriverWait(driver, LOGIN_WAIT_TIME).until(EC.element_to_be_clickable((By.ID, "username")))
    password_field = WebDriverWait(driver, LOGIN_WAIT_TIME).until(EC.element_to_be_clickable((By.ID, "password")))

    # Enter credentials
    username_field.send_keys(USERNAME)
    password_field.send_keys(PASSWORD)

    # Accept terms if checkbox is present
    terms_checkbox = driver.find_element(By.ID, "cbTerms")
    if not terms_checkbox.is_selected():
        terms_checkbox.click()

    # Locate and click the sign-in button
    sign_in_button = WebDriverWait(driver, LOGIN_WAIT_TIME).until(EC.element_to_be_clickable((By.CLASS_NAME, "btn-signin")))
    sign_in_button.click()
    # logger.info("Login submitted.")

    # Handle potential modal popup after login
    try:
        modal_popup = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, "modal-dialog")))
        close_button = WebDriverWait(modal_popup, 5).until(EC.element_to_be_clickable((By.CLASS_NAME, "close")))
        close_button.click()
        WebDriverWait(driver, 5).until(EC.invisibility_of_element(modal_popup))
        # logger.info("Popup closed.")
    except TimeoutException:
        logger.info("No modal popup detected.")

    # Wait for products table to be present
    WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, "products-table")))
    
    # Wait for Price to be present and loaded
    WebDriverWait(driver, 15).until(EC.visibility_of_element_located ((By.CLASS_NAME, "currency")))
    
    # Locate rows containing product link and amount
    row_elements = WebDriverWait(driver, WAIT_TIME).until(
        EC.presence_of_all_elements_located(
            (By.XPATH, f"//tr[contains(@class, 'product') and .//a[contains(@href, '/ecomm/product/') and contains(text(), '{partNo}')] and .//span[contains(@class, 'amount')]]")
        )
    )

    # Extract all prices from matching rows
    all_prices = []
    for row in row_elements:
        # Scroll element into view
        driver.execute_script("arguments[0].scrollIntoView(true);", row)
        price_elements = row.find_elements(By.XPATH, ".//span[contains(@class, 'amount')]")
        prices = [price.text.strip() for price in price_elements if price.text.strip()]
        all_prices.extend(prices)

    # Output all prices found for the part number
    if all_prices:
        print(",".join(all_prices))
    else:
        print(0)

except (TimeoutException, NoSuchElementException, WebDriverException) as e:
    logger.error(f"An error occurred: {e}")
    print(0)
finally:
    driver.quit()
    # logger.info("Browser closed.")
