"""
Diagnostic script to identify exact locator and page load issues
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from pages.login_page import LoginPage
from pages.mandatory_reset_page import MandatoryResetPage
from pages.profile_incomplete_page import ProfileIncompletePage
from config.config import TEST_USERNAME, TEST_PASSWORD, TEST_NEW_PASSWORD
import time

options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

try:
    print("=" * 80)
    print("DIAGNOSING LOGOUT ISSUE")
    print("=" * 80)
    
    # Login
    login_page = LoginPage(driver)
    login_page.login(TEST_USERNAME, TEST_PASSWORD)
    
    # Handle password reset
    reset_page = MandatoryResetPage(driver)
    if reset_page.is_modal_present():
        reset_page.reset_password(TEST_PASSWORD, TEST_NEW_PASSWORD, TEST_NEW_PASSWORD, TEST_USERNAME)
    
    # Handle profile incomplete
    profile_incomplete = ProfileIncompletePage(driver)
    if profile_incomplete.is_modal_present():
        profile_incomplete.click_complete()
        time.sleep(2)
    
    print(f"\nCurrent URL: {driver.current_url}")
    
    # Check for profile button
    print("\n--- PROFILE BUTTON LOCATORS ---")
    locators = [
        ("Relative div button", "//nav//div[contains(@class, 'relative')]//button"),
        ("Button with span", "//nav//button[.//span]"),
        ("Button with SVG", "//nav//button[.//*[local-name()='svg']]"),
        ("All nav buttons", "//nav//button"),
    ]
    
    for name, xpath in locators:
        try:
            elements = driver.find_elements(By.XPATH, xpath)
            print(f"{name}: Found {len(elements)} elements")
            for i, el in enumerate(elements[:3]):
                try:
                    text = el.text[:50] if el.text else "No text"
                    print(f"  Element {i+1}: text='{text}', displayed={el.is_displayed()}, enabled={el.is_enabled()}")
                except:
                    print(f"  Element {i+1}: (stale or error)")
        except Exception as e:
            print(f"{name}: Error - {e}")
    
    # Try clicking profile button
    print("\n--- ATTEMPTING PROFILE BUTTON CLICK ---")
    try:
        profile_btn = driver.find_element(By.XPATH, "//nav//div[contains(@class, 'relative')]//button")
        if profile_btn.is_displayed():
            print("Profile button found and visible")
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", profile_btn)
            time.sleep(0.5)
            profile_btn.click()
            print("Profile button clicked")
            time.sleep(2)  # Wait for dropdown
            
            # Check for sign out button
            print("\n--- SIGN OUT BUTTON LOCATORS ---")
            signout_locators = [
                ("Sign Out (capital)", "//button[contains(text(), 'Sign Out')]"),
                ("Sign out (lowercase)", "//button[contains(text(), 'Sign out')]"),
                ("Sign out (case insensitive)", "//button[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'sign out')]"),
                ("All buttons with text", "//button[text()]"),
            ]
            
            for name, xpath in signout_locators:
                try:
                    elements = driver.find_elements(By.XPATH, xpath)
                    print(f"{name}: Found {len(elements)} elements")
                    for i, el in enumerate(elements[:5]):
                        try:
                            text = el.text[:50] if el.text else "No text"
                            print(f"  Element {i+1}: text='{text}', displayed={el.is_displayed()}")
                        except:
                            print(f"  Element {i+1}: (stale or error)")
                except Exception as e:
                    print(f"{name}: Error - {e}")
        else:
            print("Profile button not displayed")
    except Exception as e:
        print(f"Error clicking profile button: {e}")
    
    print("\n" + "=" * 80)
    print("DIAGNOSING PROFILE EDITOR ISSUE")
    print("=" * 80)
    
    # Navigate to profile editor if not already there
    if "/profile-builder" not in driver.current_url:
        driver.get("http://localhost:3983/student/profile-builder")
        time.sleep(3)
    
    print(f"\nCurrent URL: {driver.current_url}")
    
    # Check for profile editor elements
    print("\n--- PROFILE EDITOR ELEMENTS ---")
    elements_to_check = [
        ("PAGE", "[data-testid='profile_editor__page']"),
        ("PROGRESS_VALUE", "[data-testid='profile_editor__progress_value']"),
        ("TAB_PERSONAL_INFORMATION", "[data-testid='profile_editor__tab_personal_information']"),
        ("Any data-testid with profile_editor", "[data-testid^='profile_editor__']"),
        ("Any tabs", "[role='tab']"),
        ("Any buttons", "button"),
    ]
    
    for name, selector in elements_to_check:
        try:
            if selector.startswith("["):
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
            else:
                elements = driver.find_elements(By.XPATH, selector)
            print(f"{name}: Found {len(elements)} elements")
            if elements:
                for i, el in enumerate(elements[:3]):
                    try:
                        text = el.text[:50] if el.text else "No text"
                        testid = el.get_attribute("data-testid") or "No testid"
                        print(f"  Element {i+1}: text='{text}', data-testid='{testid}', displayed={el.is_displayed()}")
                    except:
                        print(f"  Element {i+1}: (stale or error)")
        except Exception as e:
            print(f"{name}: Error - {e}")
    
    # Check page source for profile editor indicators
    print("\n--- PAGE SOURCE CHECK ---")
    page_source = driver.page_source.lower()
    indicators = ["profile", "editor", "builder", "personal information", "tab"]
    for indicator in indicators:
        count = page_source.count(indicator)
        print(f"'{indicator}' appears {count} times in page source")
    
except Exception as e:
    print(f"\nERROR: {e}")
    import traceback
    traceback.print_exc()
finally:
    driver.quit()

