from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

def login_to_cms():
    # Set up the Selenium WebDriver
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service)

    try:
        # Step 1: Open the CMS login page
        driver.get("https://stag-cms.unioilapps.com/login")
        print("Opened login page")

        # Step 2: Locate and fill username field
        username_field = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "username"))
        )
        username_field.send_keys("lbteksupport")
        print("Entered username")

        # Step 3: Locate and click the first Next button
        next_button1 = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "button.ant-btn.ant-btn-primary"))
        )
        next_button1.click()
        print("Clicked Next button")

        # Step 4: Locate and fill password field on the new page
        password_field = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "password"))
        )
        password_field.send_keys("7q$!jAv9!I8HNX")
        print("Entered password")

        # Step 5: Locate and click the second Next button
        next_button2 = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "button.ant-btn.ant-btn-primary"))
        )
        next_button2.click()
        print("Clicked second Next button")

        # Step 6: Verify successful login (check for My Profile)
        profile_title = WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.XPATH, "//h1[contains(text(), 'Profile')]"))
        ).text
        assert "Profile" in profile_title, f"Login failed: Expected 'Profile', got '{profile_title}'"
        print("Login test passed! Landed on My Profile")

        return driver

    except Exception as e:
        print(f"Login failed: {e}")
        driver.save_screenshot("error.png")
        print("Screenshot saved as error.png for debugging")
        driver.quit()
        raise

if __name__ == "__main__":
    try:
        driver = login_to_cms()
        print("Login successful, keeping browser open. Press Ctrl+C to close.")
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nUser interrupted the script. Closing the browser.")
        driver.quit()