from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains

driver = None

def open(url, headless=False):
    """
    Open a browser and go to the given URL.
    Set headless=True to run without showing the browser.
    """
    global driver
    if driver is None:
        options = webdriver.ChromeOptions()
        if headless:
            options.add_argument("--headless=new")
            options.add_argument("--disable-gpu")
            options.add_argument("--no-sandbox")
        service = Service(ChromeDriverManager().install())
        driver = webdriver.Chrome(service=service, options=options)
    driver.get(url)
    print(f"✅ Opened {url}")


def close():
    """Close the browser."""
    global driver
    if driver:
        driver.quit()
        driver = None
        print("✅ Browser closed")


def type(selector, text, timeout=10):
    """Type text into an input field."""
    global driver
    try:
        element = WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, selector))
        )
        element.clear()
        element.send_keys(text)
        print(f"✅ Typed '{text}' into {selector}")
    except Exception as e:
        print(f"❌ Type failed: {e}")


def enter(selector, timeout=10):
    """Press Enter on an input field."""
    global driver
    try:
        element = WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, selector))
        )
        element.send_keys(Keys.RETURN)
        print(f"✅ Enter pressed on {selector}")
    except Exception as e:
        print(f"❌ Enter failed: {e}")


def click(selector, timeout=10):
    """Click an element."""
    global driver
    try:
        element = WebDriverWait(driver, timeout).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
        )
        element.click()
        print(f"✅ Clicked {selector}")
    except Exception as e:
        print(f"❌ Click failed: {e}")


def hover(selector, timeout=10):
    """Hover over an element."""
    global driver
    try:
        element = WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, selector))
        )
        ActionChains(driver).move_to_element(element).perform()
        print(f"✅ Hovered over {selector}")
    except Exception as e:
        print(f"❌ Hover failed: {e}")


def scroll(pixels=500):
    """Scroll the page vertically by the given number of pixels."""
    global driver
    try:
        driver.execute_script(f"window.scrollBy(0, {pixels});")
        print(f"✅ Scrolled down {pixels} pixels")
    except Exception as e:
        print(f"❌ Scroll failed: {e}")


def refresh():
    """Refresh the current page."""
    global driver
    try:
        driver.refresh()
        print("✅ Page refreshed")
    except Exception as e:
        print(f"❌ Refresh failed: {e}")
