"""
Comprehensive Verification Script - Testing Conditional Attributes

Purpose: Verify UI team's claims about conditional attributes
Method: Test all tabs, checkboxes, and scroll states
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

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 selenium.webdriver.common.action_chains import ActionChains
from pages.login_page import LoginPage
from pages.mandatory_reset_page import MandatoryResetPage
from config.config import TEST_USERNAME, TEST_PASSWORD, BASE_URL
import time
import json


def verify_conditional_attributes():
    """Verify all conditional attributes by testing different states"""
    print("="*80)
    print("🔍 COMPREHENSIVE CONDITIONAL ATTRIBUTE VERIFICATION")
    print("="*80)
    print("\n🎯 Purpose: Verify UI team's claims about conditional attributes")
    print("💡 Method: Test all tabs, checkboxes, and scroll states\n")
    
    results = {
        'save_button': {'found': False, 'location': None, 'notes': ''},
        'specially_abled_details': {'found': False, 'location': None, 'notes': ''},
        'scroll_left_button': {'found': False, 'location': None, 'notes': ''},
        'contact_information_tab': {'found': False, 'location': None, 'notes': ''},
        'all_tabs': []
    }
    
    # Setup Chrome driver
    chrome_options = Options()
    chrome_options.add_argument("--start-maximized")
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    
    driver = webdriver.Chrome(options=chrome_options)
    
    try:
        # Step 1: Login
        print("\n📋 Step 1: Logging in...")
        driver.get(BASE_URL + "/login")
        time.sleep(2)
        
        login_page = LoginPage(driver)
        login_page.login(identifier=TEST_USERNAME, password=TEST_PASSWORD)
        time.sleep(3)
        
        # Handle password reset if needed
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            print("⚠️  Handling password reset...")
            try:
                reset_page.click_continue()
                time.sleep(2)
                reset_page.reset_password(
                    current_password=TEST_PASSWORD,
                    new_password=TEST_PASSWORD
                )
                time.sleep(3)
            except:
                print("  ⚠️  Could not handle password reset - continuing")
        
        # Step 2: Navigate to Profile Editor
        print("\n📋 Step 2: Navigating to Profile Editor...")
        driver.get(BASE_URL + "/student/profile-builder")
        time.sleep(5)
        
        # Wait for page load
        WebDriverWait(driver, 10).until(
            lambda d: d.execute_script("return document.readyState") == "complete"
        )
        time.sleep(2)
        
        # Step 3: Find all tabs
        print("\n📋 Step 3: Finding all tabs...")
        tabs = driver.find_elements(By.CSS_SELECTOR, "[data-testid^='profile_editor__tab_']")
        print(f"  Found {len(tabs)} tabs")
        
        tab_names = []
        for tab in tabs:
            test_id = tab.get_attribute('data-testid')
            tab_names.append(test_id)
            print(f"    - {test_id}")
        
        results['all_tabs'] = tab_names
        
        # Step 4: Check for Contact Information tab
        print("\n📋 Step 4: Checking for Contact Information tab...")
        contact_tab = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__tab_contact_information']")
        if contact_tab:
            results['contact_information_tab'] = {'found': True, 'location': 'Separate tab', 'notes': 'Found as separate tab'}
            print("  ✅ Contact Information found as separate tab")
        else:
            # Check if it's merged with Personal Information
            personal_tab = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__tab_personal_information']")
            if personal_tab:
                results['contact_information_tab'] = {'found': False, 'location': 'Merged with Personal Information', 'notes': 'Not a separate tab - merged correctly'}
                print("  ✅ Contact Information is merged with Personal Information (correct)")
        
        # Step 5: Navigate to last tab to find Save button
        print("\n📋 Step 5: Navigating to last tab to find Save button...")
        if tabs:
            last_tab = tabs[-1]
            last_tab_test_id = last_tab.get_attribute('data-testid')
            print(f"  Clicking last tab: {last_tab_test_id}")
            
            # Scroll into view and click
            driver.execute_script("arguments[0].scrollIntoView(true);", last_tab)
            time.sleep(1)
            last_tab.click()
            time.sleep(3)
            
            # Look for Save button
            save_buttons = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__save_button']")
            if save_buttons:
                results['save_button'] = {'found': True, 'location': f'Last tab ({last_tab_test_id})', 'notes': 'Found on last tab as claimed'}
                print("  ✅ Save button FOUND on last tab!")
            else:
                results['save_button'] = {'found': False, 'location': None, 'notes': 'Not found even on last tab'}
                print("  ❌ Save button NOT FOUND even on last tab")
        else:
            print("  ⚠️  No tabs found, cannot test Save button")
        
        # Step 6: Navigate to Personal Information tab and check Specially Abled
        print("\n📋 Step 6: Testing Specially Abled details (conditional)...")
        personal_tab = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__tab_personal_information']")
        if personal_tab:
            personal_tab[0].click()
            time.sleep(2)
            
            # Check if checkbox exists
            checkbox = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__specially_abled_checkbox']")
            if checkbox:
                print("  ✅ Specially Abled checkbox found")
                
                # Check if it's already checked
                is_checked = checkbox[0].is_selected()
                print(f"  Checkbox state: {'Checked' if is_checked else 'Unchecked'}")
                
                if not is_checked:
                    print("  Clicking checkbox to trigger conditional field...")
                    checkbox[0].click()
                    time.sleep(2)
                
                # Now look for details textarea
                textarea = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__specially_abled_details_textarea']")
                if textarea:
                    results['specially_abled_details'] = {'found': True, 'location': 'Personal Information tab', 'notes': 'Found when checkbox is checked'}
                    print("  ✅ Specially Abled details textarea FOUND when checkbox checked!")
                else:
                    results['specially_abled_details'] = {'found': False, 'location': 'Personal Information tab', 'notes': 'Not found even when checkbox checked'}
                    print("  ❌ Specially Abled details textarea NOT FOUND even when checkbox checked")
            else:
                print("  ⚠️  Specially Abled checkbox not found")
        else:
            print("  ⚠️  Personal Information tab not found")
        
        # Step 7: Test scroll left button (resize window to trigger overflow)
        print("\n📋 Step 7: Testing scroll left button (conditional on overflow)...")
        # Resize window to small width to trigger tab overflow
        driver.set_window_size(400, 800)
        time.sleep(2)
        
        # Scroll tabs to the right first
        tabs_container = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__tabs_container']")
        if tabs_container:
            # Try to scroll tabs container
            driver.execute_script("arguments[0].scrollLeft = 100;", tabs_container[0])
            time.sleep(1)
        
        # Look for scroll left button
        scroll_left = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__tabs_scroll_left_button']")
        if scroll_left:
            results['scroll_left_button'] = {'found': True, 'location': 'Tabs container', 'notes': 'Found when tabs overflow'}
            print("  ✅ Scroll left button FOUND when tabs overflow!")
        else:
            # Try scrolling more
            if tabs_container:
                driver.execute_script("arguments[0].scrollLeft = 200;", tabs_container[0])
                time.sleep(1)
                scroll_left = driver.find_elements(By.CSS_SELECTOR, "[data-testid='profile_editor__tabs_scroll_left_button']")
                if scroll_left:
                    results['scroll_left_button'] = {'found': True, 'location': 'Tabs container', 'notes': 'Found when tabs overflow (after more scroll)'}
                    print("  ✅ Scroll left button FOUND after scrolling more!")
                else:
                    results['scroll_left_button'] = {'found': False, 'location': None, 'notes': 'Not found even after scrolling - may need more tabs or different window size'}
                    print("  ⚠️  Scroll left button NOT FOUND - may need more tabs or different conditions")
        
        # Restore window size
        driver.set_window_size(1920, 1080)
        time.sleep(1)
        
        # Step 8: Summary
        print("\n" + "="*80)
        print("📊 VERIFICATION SUMMARY")
        print("="*80)
        
        print(f"\n✅ Save Button: {'FOUND' if results['save_button']['found'] else 'NOT FOUND'}")
        if results['save_button']['found']:
            print(f"   Location: {results['save_button']['location']}")
        else:
            print(f"   Notes: {results['save_button']['notes']}")
        
        print(f"\n✅ Specially Abled Details: {'FOUND' if results['specially_abled_details']['found'] else 'NOT FOUND'}")
        if results['specially_abled_details']['found']:
            print(f"   Location: {results['specially_abled_details']['location']}")
        else:
            print(f"   Notes: {results['specially_abled_details']['notes']}")
        
        print(f"\n✅ Scroll Left Button: {'FOUND' if results['scroll_left_button']['found'] else 'NOT FOUND'}")
        if results['scroll_left_button']['found']:
            print(f"   Location: {results['scroll_left_button']['location']}")
        else:
            print(f"   Notes: {results['scroll_left_button']['notes']}")
        
        print(f"\n✅ Contact Information Tab: {results['contact_information_tab']['location']}")
        print(f"   Notes: {results['contact_information_tab']['notes']}")
        
        # Final verdict
        print("\n" + "="*80)
        print("🎯 FINAL VERDICT")
        print("="*80)
        
        all_found = (
            results['save_button']['found'] and
            results['specially_abled_details']['found'] and
            (results['scroll_left_button']['found'] or 'overflow' in results['scroll_left_button']['notes'].lower()) and
            'merged' in results['contact_information_tab']['notes'].lower() or results['contact_information_tab']['found']
        )
        
        if all_found:
            print("\n✅ UI TEAM'S CLAIMS ARE 100% TRUE!")
            print("   All attributes are present and work correctly with conditional rendering.")
        else:
            print("\n⚠️  UI TEAM'S CLAIMS ARE MOSTLY TRUE")
            print("   Some attributes may need different conditions to appear.")
        
        # Save results
        report_file = os.path.join(os.path.dirname(__file__), '..', 'documentation', 'verification-reports', 'CONDITIONAL_ATTRIBUTES_VERIFICATION.json')
        os.makedirs(os.path.dirname(report_file), exist_ok=True)
        with open(report_file, 'w') as f:
            json.dump(results, f, indent=2)
        
        print(f"\n💾 Detailed results saved to: {report_file}")
        print(f"\n⏸️  Browser will stay open for 30 seconds for manual inspection...")
        time.sleep(30)
        
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
        print(f"\n⏸️  Browser will stay open for 30 seconds for manual inspection...")
        time.sleep(30)
    finally:
        print(f"\n{'='*80}")
        print("CLEANUP")
        print(f"{'='*80}")
        driver.quit()
        print("✅ Driver closed")


if __name__ == "__main__":
    verify_conditional_attributes()


