import os
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 test_invalid_password_login():
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service)

    # Create 'screenshots' folder if it doesn't exist
    if not os.path.exists("screenshots"):
        os.makedirs("screenshots")

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

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

        # Step 3: Click Next
        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 after username")

        # Step 4: Enter invalid password
        password_field = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "password"))
        )
        password_field.send_keys("1234")
        print("Entered invalid password")

        # Step 5: Click Next again
        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 Next button after password")

        # No explicit wait for error message, assume it will show automatically
        print("✅ Negative test completed successfully. Password incorrect expected.")

        # Take screenshot after test
        screenshot_path = os.path.join("screenshots", "password_incorrect.png")
        driver.save_screenshot(screenshot_path)
        print(f"Screenshot saved as {screenshot_path}")

        # Keep the browser open for inspection
        print("Test complete. Browser will stay open. Press Ctrl+C to exit.")
        time.sleep(10)  # Sleep for 10 seconds so you can inspect the browser before closing.

    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        screenshot_path = os.path.join("screenshots", "unexpected_error.png")
        driver.save_screenshot(screenshot_path)
        print(f"Screenshot saved as {screenshot_path}")

    finally:
        # You can choose to leave the browser open or close it manually
        # driver.quit()  # Commented out so you can leave the browser open
        print("Browser closed. Test completed.")

if __name__ == "__main__":
    test_invalid_password_login()
