"""
Debug script to test password reset flow
"""
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 pages.login_page import LoginPage
from pages.mandatory_reset_page import MandatoryResetPage
from utils.password_tracker import password_tracker
from config.config import TEST_USERNAME, TEST_PASSWORD, TEST_NEW_PASSWORD, BASE_URL
import time

def debug_password_reset():
    """Debug password reset flow"""
    print("=" * 80)
    print("🔍 DEBUGGING PASSWORD RESET FLOW")
    print("=" * 80)
    
    # 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:
        print(f"\n📋 Test Configuration:")
        print(f"  TEST_USERNAME: {TEST_USERNAME}")
        print(f"  TEST_PASSWORD: {TEST_PASSWORD}")
        print(f"  TEST_NEW_PASSWORD: {TEST_NEW_PASSWORD}")
        print(f"  BASE_URL: {BASE_URL}")
        
        print(f"\n📊 Password Tracker State (BEFORE):")
        print(f"  Tracked password: {password_tracker.get_password(TEST_USERNAME, TEST_PASSWORD)}")
        print(f"  Tracker state: {password_tracker._passwords}")
        
        # Step 1: Login
        print(f"\n{'='*80}")
        print("STEP 1: LOGIN")
        print("="*80)
        login_page = LoginPage(driver)
        login_page.login(identifier=TEST_USERNAME, password=TEST_PASSWORD)
        print(f"✅ Login completed")
        print(f"  Current URL: {driver.current_url}")
        time.sleep(2)
        
        # Step 2: Check for password reset modal
        print(f"\n{'='*80}")
        print("STEP 2: CHECK FOR PASSWORD RESET MODAL")
        print("="*80)
        reset_page = MandatoryResetPage(driver)
        
        # Check modal presence with detailed logging
        print(f"\n🔍 Checking modal presence...")
        modal_present = reset_page.is_modal_present()
        print(f"  is_modal_present() returned: {modal_present}")
        
        if modal_present:
            print(f"✅ Modal is present - password reset needed")
            
            # Check what step we're on
            try:
                continue_button = driver.find_element(reset_page.CONTINUE_BUTTON[0], reset_page.CONTINUE_BUTTON[1])
                if continue_button.is_displayed():
                    print(f"  📋 Step 1: Welcome screen (Continue button visible)")
                else:
                    print(f"  📋 Step 2: Form screen (Continue button not visible)")
            except:
                print(f"  ⚠️  Could not determine step")
            
            # Try to reset password
            print(f"\n{'='*80}")
            print("STEP 3: RESET PASSWORD")
            print("="*80)
            try:
                reset_page.reset_password(
                    current_password=TEST_PASSWORD,
                    new_password=TEST_NEW_PASSWORD,
                    confirm_password=TEST_NEW_PASSWORD,
                    student_cpid=TEST_USERNAME
                )
                print(f"✅ Password reset completed successfully")
            except Exception as e:
                print(f"❌ Password reset failed: {e}")
                import traceback
                traceback.print_exc()
        else:
            print(f"⚠️  Modal is NOT present")
            print(f"  This means either:")
            print(f"    1. Password was already reset")
            print(f"    2. Modal detection is failing")
            print(f"    3. Student doesn't need password reset")
            
            # Check page source for clues
            page_source = driver.page_source.lower()
            if "welcome to cognitive prism" in page_source:
                print(f"  🔍 Found 'Welcome to Cognitive Prism' in page source")
            if "reset your password" in page_source:
                print(f"  🔍 Found 'Reset your password' in page source")
            if "mandatory" in page_source:
                print(f"  🔍 Found 'mandatory' in page source")
        
        # Step 3: Check password tracker
        print(f"\n{'='*80}")
        print("STEP 3: CHECK PASSWORD TRACKER")
        print("="*80)
        print(f"  Tracked password: {password_tracker.get_password(TEST_USERNAME, TEST_PASSWORD)}")
        print(f"  Tracker state: {password_tracker._passwords}")
        
        # Step 4: Try login with new password
        print(f"\n{'='*80}")
        print("STEP 4: VERIFY PASSWORD RESET (Login with new password)")
        print("="*80)
        driver.get(BASE_URL + "/login")
        time.sleep(2)
        
        login_page2 = LoginPage(driver)
        try:
            login_page2.login(identifier=TEST_USERNAME, password=TEST_NEW_PASSWORD)
            print(f"✅ Login with TEST_NEW_PASSWORD succeeded - password reset worked!")
        except Exception as e:
            print(f"❌ Login with TEST_NEW_PASSWORD failed: {e}")
            print(f"  This suggests password reset did NOT work")
        
        time.sleep(5)
        
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
    finally:
        print(f"\n{'='*80}")
        print("CLEANUP")
        print("="*80)
        driver.quit()
        print("✅ Driver closed")

if __name__ == "__main__":
    debug_password_reset()


