"""
Debug script to inspect question 29 in domain assessment
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from pages.login_page import LoginPage
from pages.mandatory_reset_page import MandatoryResetPage
from pages.profile_incomplete_page import ProfileIncompletePage
from pages.assessments_page import AssessmentsPage
from pages.domains_page import DomainsPage
from pages.domain_assessment_page import DomainAssessmentPage
from utils.password_tracker import password_tracker
from utils.student_data_manager import student_data_manager
from config.config import TEST_NEW_PASSWORD
import time

def debug_question_29():
    """Debug question 29 to see actual DOM structure"""
    driver = webdriver.Chrome()
    driver.maximize_window()
    
    try:
        # Load student data
        student_data_manager.load_students_from_csv()
        students = student_data_manager._students
        cpid = list(students.keys())[0]
        
        print(f"🔍 Debugging question 29 for student: {cpid}")
        
        # Login
        login_page = LoginPage(driver)
        tracked_password = password_tracker.get_password(cpid, students[cpid].get('password'))
        password_to_use = tracked_password if tracked_password != students[cpid].get('password') else TEST_NEW_PASSWORD
        login_page.login(identifier=cpid, password=password_to_use)
        time.sleep(3)
        
        # Navigate to assessment
        assessments_page = AssessmentsPage(driver)
        assessments_page.navigate()
        assessments_page.wait_for_page_load()
        time.sleep(2)
        
        # Get first assessment
        assessment_ids = assessments_page.get_assessment_ids()
        if not assessment_ids:
            print("❌ No assessments found")
            return
        
        assessment_id = assessment_ids[0]
        print(f"📋 Using assessment ID: {assessment_id}")
        
        # Click assessment
        assessments_page.click_begin_assessment(assessment_id)
        time.sleep(2)
        
        # Navigate to first domain
        domains_page = DomainsPage(driver)
        domains_page.wait_for_page_load()
        time.sleep(2)
        
        # Get first domain
        domain_ids = domains_page.get_all_domain_ids()
        if not domain_ids:
            print("❌ No domains found")
            return
        
        domain_id = domain_ids[0]
        print(f"🎯 Using domain ID: {domain_id}")
        
        # Click domain
        domains_page.click_domain_action(domain_id)
        time.sleep(3)
        
        # Dismiss instructions modal
        assessment_page = DomainAssessmentPage(driver)
        if assessment_page.is_instructions_modal_present():
            assessment_page.dismiss_instructions_modal()
            time.sleep(2)
        
        # Navigate to question 29 (or find it)
        print("\n🔍 Inspecting question 29...")
        
        # Find question 29 element
        question_29_selector = "[data-testid='domain_question__29']"
        try:
            question_elem = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, question_29_selector))
            )
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", question_elem)
            time.sleep(2)
            
            print(f"\n✅ Found question 29 element")
            print(f"   data-testid: {question_elem.get_attribute('data-testid')}")
            print(f"   HTML:\n{question_elem.get_attribute('outerHTML')[:500]}")
            
            # Check for all possible answer elements
            print("\n🔍 Checking for answer elements...")
            
            # Check rating scale
            for rating in ['1', '2', '3', '4', '5']:
                rating_selector = f"[data-testid='domain_question__29__rating_{rating}']"
                try:
                    rating_elem = driver.find_element(By.CSS_SELECTOR, rating_selector)
                    print(f"   ✅ Found rating_{rating}: {rating_elem.get_attribute('data-testid')}")
                    print(f"      Text: {rating_elem.text}")
                    print(f"      Visible: {rating_elem.is_displayed()}")
                except:
                    print(f"   ❌ Not found: rating_{rating}")
            
            # Check multiple choice
            for label in ['A', 'B', 'C', 'D', 'E']:
                option_selector = f"[data-testid='domain_question__29__option_{label}']"
                try:
                    option_elem = driver.find_element(By.CSS_SELECTOR, option_selector)
                    print(f"   ✅ Found option_{label}: {option_elem.get_attribute('data-testid')}")
                except:
                    pass
            
            # Check true/false
            for value in ['True', 'False']:
                tf_selector = f"[data-testid='domain_question__29__truefalse_{value}']"
                try:
                    tf_elem = driver.find_element(By.CSS_SELECTOR, tf_selector)
                    print(f"   ✅ Found truefalse_{value}: {tf_elem.get_attribute('data-testid')}")
                except:
                    pass
            
            # Check open ended
            textarea_selector = f"[data-testid='domain_question__29__textarea']"
            try:
                textarea_elem = driver.find_element(By.CSS_SELECTOR, textarea_selector)
                print(f"   ✅ Found textarea: {textarea_elem.get_attribute('data-testid')}")
            except:
                pass
            
            # Check matrix
            matrix_selector = f"[data-testid^='domain_question__29__matrix_']"
            try:
                matrix_elems = driver.find_elements(By.CSS_SELECTOR, matrix_selector)
                if matrix_elems:
                    print(f"   ✅ Found {len(matrix_elems)} matrix cells")
                    for i, cell in enumerate(matrix_elems[:3]):  # Show first 3
                        print(f"      Cell {i}: {cell.get_attribute('data-testid')}")
            except:
                pass
            
            # Check containers
            print("\n🔍 Checking for container elements...")
            containers = ['multiple_choice', 'true_false', 'rating_scale', 'open_ended', 'matrix']
            for container in containers:
                container_selector = f"[data-testid='domain_question__29__{container}']"
                try:
                    container_elem = driver.find_element(By.CSS_SELECTOR, container_selector)
                    print(f"   ✅ Found {container} container: {container_elem.get_attribute('data-testid')}")
                except:
                    pass
            
            # Get all elements with data-testid containing "29"
            print("\n🔍 All elements with '29' in data-testid:")
            all_29_elements = driver.find_elements(By.CSS_SELECTOR, "[data-testid*='29']")
            for elem in all_29_elements:
                test_id = elem.get_attribute('data-testid')
                tag = elem.tag_name
                text = elem.text[:50] if elem.text else ""
                visible = elem.is_displayed()
                print(f"   - {test_id} ({tag}) - Visible: {visible} - Text: {text}")
            
        except TimeoutException:
            print("❌ Question 29 not found on current page")
            print("   Current URL:", driver.current_url)
            print("   Trying to find any question...")
            
            # Find any question
            any_question = driver.find_elements(By.CSS_SELECTOR, "[data-testid^='domain_question__']")
            print(f"   Found {len(any_question)} question elements")
            for i, q in enumerate(any_question[:5]):
                test_id = q.get_attribute('data-testid')
                print(f"   Question {i+1}: {test_id}")
        
        print("\n⏸️  Pausing for 30 seconds to inspect manually...")
        time.sleep(30)
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()
    finally:
        driver.quit()

if __name__ == "__main__":
    debug_question_29()

