"""
Direct DOM Verification for Toast Attributes

This script directly inspects the DOM to verify toast attributes are present.
Uses browser automation to trigger toasts and check DOM.
"""
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 selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from config.config import BASE_URL
import time

def check_dom_for_attribute(driver, test_id, description):
    """Check DOM directly for attribute"""
    print(f"\n🔍 Checking DOM for: {description}")
    print(f"   Attribute: [data-testid='{test_id}']")
    
    # Check page source first
    page_source = driver.page_source
    if test_id in page_source:
        print(f"   ✅ Found in page source")
    else:
        print(f"   ❌ Not found in page source")
    
    # Check DOM elements
    try:
        elements = driver.find_elements(By.CSS_SELECTOR, f"[data-testid='{test_id}']")
        if elements:
            print(f"   ✅ Found {len(elements)} element(s) in DOM")
            for i, elem in enumerate(elements):
                print(f"      Element {i+1}:")
                print(f"         - Visible: {elem.is_displayed()}")
                print(f"         - Role: {elem.get_attribute('role')}")
                print(f"         - Text: {elem.text[:50] if elem.text else 'N/A'}")
            return True
        else:
            print(f"   ❌ No elements found in DOM")
            return False
    except Exception as e:
        print(f"   ❌ Error checking DOM: {e}")
        return False

def main():
    print("=" * 70)
    print("DIRECT DOM VERIFICATION FOR TOAST ATTRIBUTES")
    print("=" * 70)
    
    options = Options()
    # Run in non-headless mode to see what's happening
    # options.add_argument('--headless=new')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    driver = webdriver.Chrome(options=options)
    driver.implicitly_wait(5)
    
    try:
        # 1. Test Login Error Toast
        print("\n" + "=" * 70)
        print("1. LOGIN ERROR TOAST VERIFICATION")
        print("=" * 70)
        
        driver.get(BASE_URL)
        time.sleep(3)
        
        # Enter invalid credentials
        identifier_input = driver.find_element(By.CSS_SELECTOR, "[data-testid='student_login__identifier_input']")
        password_input = driver.find_element(By.CSS_SELECTOR, "[data-testid='student_login__password_input']")
        submit_button = driver.find_element(By.CSS_SELECTOR, "[data-testid='student_login__submit_button']")
        
        identifier_input.clear()
        identifier_input.send_keys("INVALID_USER_12345")
        password_input.clear()
        password_input.send_keys("INVALID_PASS_12345")
        
        # Click submit using JavaScript
        driver.execute_script("arguments[0].click();", submit_button)
        
        # Wait for toast to appear and data-testid to be added
        print("\n   Waiting for toast to appear...")
        for i in range(15):  # Wait up to 1.5 seconds (toast helper max is 1 second)
            time.sleep(0.1)
            
            # Check for toast with data-testid
            toasts = driver.find_elements(By.CSS_SELECTOR, "[data-testid='student_login__error_toast']")
            if toasts:
                visible_toasts = [t for t in toasts if t.is_displayed()]
                if visible_toasts:
                    print(f"   ✅ Toast found with data-testid (attempt {i+1})")
                    toast = visible_toasts[0]
                    print(f"      - Text: {toast.text}")
                    print(f"      - Role: {toast.get_attribute('role')}")
                    print(f"      - Aria-live: {toast.get_attribute('aria-live')}")
                    break
            
            # Also check for any toast with role="status" (fallback check)
            if i == 14:  # Last attempt
                status_toasts = driver.find_elements(By.CSS_SELECTOR, "[role='status']")
                if status_toasts:
                    print(f"   ⚠️  Found {len(status_toasts)} toast(s) with role='status' but no data-testid")
                    for t in status_toasts:
                        if t.is_displayed():
                            print(f"      - Text: {t.text}")
                            print(f"      - Has data-testid: {t.get_attribute('data-testid')}")
        
        # Final check
        result = check_dom_for_attribute(driver, 'student_login__error_toast', 'Login Error Toast')
        
        # 2. Check static attributes (assessment header, question counter)
        print("\n" + "=" * 70)
        print("2. STATIC ATTRIBUTES VERIFICATION")
        print("=" * 70)
        print("   Note: These require navigation to assessment page")
        print("   Will check if we can navigate...")
        
        # Try to login first
        driver.get(BASE_URL)
        time.sleep(2)
        
        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 config.config import TEST_USERNAME, TEST_NEW_PASSWORD
        
        login_page = LoginPage(driver)
        try:
            login_page.login(TEST_USERNAME, TEST_NEW_PASSWORD)
            time.sleep(3)
            
            # Navigate to assessments
            assessments_page = AssessmentsPage(driver)
            assessments_page.navigate()
            assessments_page.wait_for_page_load()
            time.sleep(2)
            
            assessment_ids = assessments_page.get_assessment_ids()
            if assessment_ids:
                assessments_page.click_begin_assessment(assessment_ids[0])
                time.sleep(3)
                
                domains_page = DomainsPage(driver)
                domains_page.wait_for_page_load()
                time.sleep(2)
                
                domain_ids = domains_page.get_all_domain_ids()
                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 unlocked_domain_id:
                    domains_page.click_start_domain(unlocked_domain_id)
                    time.sleep(5)
                    
                    domain_assessment = DomainAssessmentPage(driver)
                    if domain_assessment.is_instructions_modal_present():
                        domain_assessment.dismiss_instructions_modal()
                        time.sleep(2)
                    
                    # Check product name
                    print("\n   Checking Assessment Header Product Name...")
                    result1 = check_dom_for_attribute(
                        driver, 
                        'domain_assessment__header__product_name',
                        'Assessment Header Product Name'
                    )
                    
                    # Check question counter
                    print("\n   Checking Question Counter...")
                    result2 = check_dom_for_attribute(
                        driver,
                        'domain_assessment__action_bar__question_counter',
                        'Question Counter'
                    )
                else:
                    print("   ⚠️  No unlocked domain found")
            else:
                print("   ⚠️  No assessments found")
        except Exception as e:
            print(f"   ⚠️  Could not navigate to assessment: {e}")
        
        print("\n" + "=" * 70)
        print("VERIFICATION COMPLETE")
        print("=" * 70)
        
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
    finally:
        input("\nPress Enter to close browser...")
        driver.quit()

if __name__ == "__main__":
    main()


