"""
Debug script to inspect question structure on domain assessment page
"""
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from utils.driver_manager import DriverManager
from pages.login_page import LoginPage
from pages.assessments_page import AssessmentsPage
from pages.domains_page import DomainsPage
from pages.domain_assessment_page import DomainAssessmentPage
from utils.student_data_manager import student_data_manager
from utils.password_tracker import password_tracker
from utils.smart_wait_optimizer import SmartWaitOptimizer
from config.config import TEST_NEW_PASSWORD
import time

def debug_question_detection():
    """Debug question detection on domain assessment page"""
    driver = DriverManager.get_driver()
    
    try:
        # Load student data
        student_data_manager.load_students_from_csv()
        students = student_data_manager._students
        if not students:
            print("❌ No student data loaded")
            return
        
        cpid = list(students.keys())[0]
        student_data = students[cpid]
        
        print(f"\n🔍 Debugging Question Detection for: {cpid}")
        
        # Login
        login_page = LoginPage(driver)
        tracked_password = password_tracker.get_password(cpid, student_data.get('password'))
        password_to_use = tracked_password if tracked_password != student_data.get('password') else None
        login_page.login(identifier=cpid, password=password_to_use)
        
        # Smart wait
        actual_password_used = tracked_password if tracked_password != student_data.get('password') else TEST_NEW_PASSWORD
        SmartWaitOptimizer.smart_wait_for_dashboard(driver, cpid, actual_password_used)
        
        # Navigate to assessments
        assessments_page = AssessmentsPage(driver)
        assessments_page.navigate()
        assessments_page.wait_for_page_load()
        
        # Start assessment
        assessment_ids = assessments_page.get_assessment_ids()
        if not assessment_ids:
            print("❌ No assessments available")
            return
        
        assessments_page.click_begin_assessment(assessment_ids[0])
        
        # Navigate to domains
        domains_page = DomainsPage(driver)
        domains_page.wait_for_page_load()
        
        # Get first unlocked domain
        domain_ids = domains_page.get_all_domain_ids()
        if not domain_ids:
            print("❌ No domains available")
            return
        
        unlocked_domain_id = None
        for domain_id in domain_ids:
            if domains_page.is_domain_unlocked(domain_id):
                unlocked_domain_id = domain_id
                break
        
        if not unlocked_domain_id:
            print("❌ No unlocked domains")
            return
        
        print(f"✅ Starting domain: {unlocked_domain_id}")
        domains_page.click_start_domain(unlocked_domain_id)
        
        # Get domain assessment page
        domain_assessment_page = DomainAssessmentPage(driver)
        domain_assessment_page.wait_for_page_load()
        time.sleep(2)
        
        # Dismiss instructions modal
        if domain_assessment_page.is_instructions_modal_present():
            print("📋 Dismissing instructions modal...")
            domain_assessment_page.dismiss_instructions_modal()
            time.sleep(2)
        
        # Now inspect the page
        print("\n🔍 INSPECTING PAGE STRUCTURE:")
        print(f"Current URL: {driver.current_url}")
        
        # Check for question elements
        question_elements = driver.find_elements(By.CSS_SELECTOR, "[data-testid^='domain_question__']")
        print(f"\n📊 Found {len(question_elements)} question-related elements")
        
        for i, elem in enumerate(question_elements[:10]):  # First 10
            test_id = elem.get_attribute("data-testid")
            tag = elem.tag_name
            visible = elem.is_displayed()
            print(f"  {i+1}. {test_id} ({tag}) - Visible: {visible}")
        
        # Try to get current question ID
        question_helper = __import__('utils.question_answer_helper', fromlist=['QuestionAnswerHelper']).QuestionAnswerHelper(driver)
        question_id = question_helper.get_question_id()
        print(f"\n🎯 Detected Question ID: {question_id}")
        
        if question_id:
            question_type = question_helper.get_question_type(question_id)
            print(f"📋 Detected Question Type: {question_type}")
            
            # Check each type specifically
            print("\n🔍 Checking each question type:")
            checks = [
                ("Multiple Choice", f"[data-testid='domain_question__{question_id}__multiple_choice']"),
                ("Multiple Choice Option A", f"[data-testid='domain_question__{question_id}__option_A']"),
                ("True/False", f"[data-testid='domain_question__{question_id}__true_false']"),
                ("True/False True", f"[data-testid='domain_question__{question_id}__truefalse_True']"),
                ("Rating Scale", f"[data-testid='domain_question__{question_id}__rating_scale']"),
                ("Rating 1", f"[data-testid='domain_question__{question_id}__rating_1']"),
                ("Open Ended", f"[data-testid='domain_question__{question_id}__open_ended']"),
                ("Open Ended Textarea", f"[data-testid='domain_question__{question_id}__textarea']"),
                ("Matrix", f"[data-testid='domain_question__{question_id}__matrix']"),
                ("Matrix Cell", f"[data-testid^='domain_question__{question_id}__matrix_']"),
            ]
            
            for check_name, selector in checks:
                try:
                    elem = driver.find_element(By.CSS_SELECTOR, selector)
                    visible = elem.is_displayed()
                    print(f"  ✅ {check_name}: Found (Visible: {visible})")
                except:
                    print(f"  ❌ {check_name}: Not found")
        
        # Get page source snippet
        print("\n📄 Page Source Snippet (first 5000 chars):")
        page_source = driver.page_source
        if "domain_question__" in page_source:
            idx = page_source.find("domain_question__")
            snippet = page_source[max(0, idx-200):idx+2000]
            print(snippet)
        
        print("\n✅ Debug complete - keeping browser open for 30 seconds...")
        time.sleep(30)
        
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
    finally:
        print("\n🔚 Closing browser...")
        DriverManager.quit_driver(driver)

if __name__ == "__main__":
    debug_question_detection()


