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
from selenium.webdriver.common.keys import Keys
import time
import sys
import os

try:
    from login import login_to_cms
    print("✅ Successfully imported login_to_cms from login.py")
except ImportError as e:
    print(f"❌ Failed to import login_to_cms: {e}")
    sys.exit(1)

def test_system_parameters():
    driver = None
    try:
        driver = login_to_cms()
        print("✅ Logged in to CMS")

        # Wait for sidebar to load
        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "li.ant-menu-item, li.ant-menu-submenu"))
        )
        print("✅ Sidebar loaded")
        time.sleep(1)

        # Click System Parameters menu item
        system_parameters_link = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//a[@href='/system-parameters']"))
        )
        system_parameters_link.click()
        print("✅ Clicked 'System Parameters'")
        time.sleep(2)

        # Click Sync Data button
        sync_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Sync Data']]"))
        )
        sync_button.click()
        print("✅ Clicked 'Sync Data' button")
        time.sleep(2)

    except Exception as e:
        print(f"❌ Test failed: {e}")
    finally:
        if driver:
            print("⏳ Waiting 10 seconds before closing browser...")
            time.sleep(10)
            driver.quit()
            print("🧹 Browser closed")

if __name__ == "__main__":
    test_system_parameters()
