from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

# Configurations
USERNAME = "mdr1"  # Replace with actual username
PASSWORD = "1217"  # Replace with actual password
PART_NO = "dw1494"  # Replace with the part number you want to search

# Setup Selenium WebDriver (Ensure chromedriver is installed)
options = webdriver.ChromeOptions()
options.add_argument("--headless")  # Run in headless mode (no GUI)
options.add_argument("--disable-gpu")  # Disable GPU for performance
options.add_argument("--no-sandbox")  # Bypass OS security model
driver = webdriver.Chrome(options=options)

try:
    # 1. Open Login Page
    driver.get("https://www.mygrantglass.com/pages/login.aspx")
    time.sleep(2)  # Allow time for page to load

    # 2. Locate login fields and submit credentials
    driver.find_element(By.NAME, "clogin:TxtUsername").send_keys(USERNAME)
    driver.find_element(By.NAME, "clogin:TxtPassword").send_keys(PASSWORD)
    driver.find_element(By.NAME, "clogin:ButtonLogin").click()
    time.sleep(3)  # Wait for login to process

    # 3. Navigate to part search page
    search_url = f"https://www.mygrantglass.com/pages/search.aspx?q={PART_NO}&sc=n&do=Search"
    driver.get(search_url)
    time.sleep(2)

    # 4. Extract Price
    price_elements = driver.find_elements(By.XPATH, "//td[contains(@class, 'price')]")

    if price_elements:
        price_text = price_elements[0].text.strip()
        price = float(price_text.replace('$', '').replace(',', ''))

        if price < 50:
            print(f"ALERT: Part {PART_NO} found for ${price} (below $50)")
        else:
            print(f"Part {PART_NO} Price: ${price}")

    else:
        print(f"No price found for Part {PART_NO}")

finally:
    driver.quit()  # Close the browser