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 negative_login_test():
    # Set up the Selenium WebDriver
    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 an invalid username
        username_field = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "username"))
        )
        username_field.clear()
        username_field.send_keys("lbtek")  # Invalid username
        print("Entered invalid username: lbtek")

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

        # Step 4: Wait for and validate the error message
        error_message = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), 'Username does not exist')]"))
        )
        print(f"❌ Login failed as expected: {error_message.text}")

        # Save screenshot to the 'screenshots' folder
        screenshot_path = os.path.join("screenshots", "wrong_username.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"❌ Test failed with error: {e}")
        screenshot_path = os.path.join("screenshots", "wrong_username.png")
        driver.save_screenshot(screenshot_path)
        print(f"Screenshot saved as {screenshot_path}")
        driver.quit()
        raise

    except KeyboardInterrupt:
        print("\n👋 User interrupted the script. Closing the browser.")
        driver.quit()

if __name__ == "__main__":
    negative_login_test()
