#!/usr/bin/env python3
"""
Complete End-to-End Flow Test

Tests the complete flow:
1. Authentication (Login → Password Reset if needed)
2. Profile Completion (to 100%)
3. Assessment Navigation

This is a comprehensive test to verify everything works smoothly.
"""
import sys
from pathlib import Path
import time

project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from pages.login_page import LoginPage
from pages.mandatory_reset_page import MandatoryResetPage
from pages.profile_incomplete_page import ProfileIncompletePage
from pages.profile_editor_page import ProfileEditorPage
from pages.dashboard_page import DashboardPage
from pages.assessments_page import AssessmentsPage
from utils.driver_manager import DriverManager
from config.config import TEST_NEW_PASSWORD, BASE_URL, TEST_USERNAME, TEST_PASSWORD


def test_complete_flow():
    """Test complete flow: Auth → Profile → Assessment"""
    driver = None
    try:
        print("="*80)
        print("🚀 COMPLETE END-TO-END FLOW TEST")
        print("="*80)
        print(f"🌐 Environment: {BASE_URL}")
        print(f"🔑 Credentials: {TEST_USERNAME}")
        print("="*80)
        
        # Initialize driver
        driver_manager = DriverManager()
        driver = driver_manager.get_driver(headless=False)
        driver.maximize_window()
        
        # ============================================================
        # PHASE 1: AUTHENTICATION
        # ============================================================
        print("\n" + "="*80)
        print("PHASE 1: AUTHENTICATION")
        print("="*80)
        
        # Step 1: Login
        print("\n📝 Step 1.1: Login")
        login_page = LoginPage(driver)
        login_page.login(identifier=TEST_USERNAME, password=TEST_PASSWORD)
        time.sleep(2)
        print(f"✅ Login successful - URL: {driver.current_url}")
        
        # Step 2: Handle Password Reset (if needed)
        print("\n📝 Step 1.2: Password Reset Check")
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            print("🔄 Password reset modal present - resetting password...")
            reset_page.reset_password(
                current_password=TEST_PASSWORD,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD,
                student_cpid=TEST_USERNAME
            )
            time.sleep(2)
            print("✅ Password reset completed")
        else:
            print("✅ No password reset required")
        
        # ============================================================
        # PHASE 2: PROFILE COMPLETION
        # ============================================================
        print("\n" + "="*80)
        print("PHASE 2: PROFILE COMPLETION")
        print("="*80)
        
        # Step 1: Handle Profile Incomplete Modal (if present)
        print("\n📝 Step 2.1: Profile Incomplete Modal Check")
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            progress = profile_incomplete.get_progress_value()
            print(f"⚠️  Profile incomplete modal present - Current progress: {progress}")
            print("🔄 Clicking 'Complete Profile Now'...")
            profile_incomplete.click_complete()
            time.sleep(3)
            print("✅ Navigated to profile editor")
        else:
            print("✅ No profile incomplete modal - navigating to profile editor...")
            profile_editor = ProfileEditorPage(driver)
            profile_editor.navigate()
            time.sleep(3)
        
        # Step 2: Complete Profile to 100%
        print("\n📝 Step 2.2: Complete Profile to 100%")
        profile_editor = ProfileEditorPage(driver)
        profile_editor.wait_for_page_load()
        
        # Check current progress
        initial_progress = profile_editor.get_progress_value()
        print(f"📊 Initial Profile Progress: {initial_progress}")
        
        if "100%" in initial_progress or initial_progress == "100":
            print("✅ Profile is already 100% complete!")
        else:
            print("🔄 Completing profile to 100%...")
            success = profile_editor.complete_profile_to_100()
            
            if success:
                final_progress = profile_editor.get_progress_value()
                print(f"\n✅ Profile completion successful!")
                print(f"📊 Final Profile Progress: {final_progress}")
            else:
                final_progress = profile_editor.get_progress_value()
                print(f"\n⚠️  Profile completion may not have reached 100%")
                print(f"📊 Final Profile Progress: {final_progress}")
                # Wait a bit for backend to update completion percentage
                print("⏳ Waiting for backend to update completion percentage...")
                time.sleep(5)
                # Check progress again
                updated_progress = profile_editor.get_progress_value()
                print(f"📊 Updated Profile Progress: {updated_progress}")
                # Don't fail - continue to assessment
        
        # ============================================================
        # PHASE 3: ASSESSMENT NAVIGATION
        # ============================================================
        print("\n" + "="*80)
        print("PHASE 3: ASSESSMENT NAVIGATION")
        print("="*80)
        
        # Step 1: Navigate to Dashboard
        print("\n📝 Step 3.1: Navigate to Dashboard")
        dashboard = DashboardPage(driver)
        dashboard.navigate()
        time.sleep(2)
        print(f"✅ Dashboard loaded - URL: {driver.current_url}")
        
        # Step 2: Handle Profile Incomplete Modal (if still present)
        print("\n📝 Step 3.2: Check for Profile Incomplete Modal")
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            progress = profile_incomplete.get_progress_value()
            print(f"⚠️  Profile incomplete modal still present - Progress: {progress}")
            print("🔄 Clicking 'Complete Profile Now' to dismiss...")
            try:
                profile_incomplete.click_complete()
                time.sleep(2)
                print("✅ Modal dismissed")
            except Exception as e:
                print(f"⚠️  Could not dismiss modal: {e}")
                # Try to close modal by clicking outside or ESC key
                try:
                    driver.execute_script("document.querySelector('[data-testid=\"profile_incomplete__modal\"]').remove();")
                    time.sleep(1)
                    print("✅ Modal removed via JavaScript")
                except:
                    pass
        
        # Step 3: Navigate to Assessments
        print("\n📝 Step 3.3: Navigate to Assessments Page")
        try:
            # Use student nav page for more robust navigation
            from pages.student_nav_page import StudentNavPage
            nav = StudentNavPage(driver)
            nav.click_assessments()
            time.sleep(3)
            print(f"✅ Assessments page loaded - URL: {driver.current_url}")
            
            # Verify we're on assessments page
            assessments = AssessmentsPage(driver)
            assessments.wait_for_page_load()
            
            # Get assessment cards
            assessment_ids = assessments.get_assessment_ids()
            if assessment_ids:
                print(f"✅ Found {len(assessment_ids)} assessment(s): {assessment_ids}")
            else:
                print("⚠️  No assessments found (may be expected if none assigned)")
            
        except Exception as e:
            print(f"⚠️  Could not navigate to assessments: {e}")
            print(f"   Current URL: {driver.current_url}")
        
        # ============================================================
        # FINAL SUMMARY
        # ============================================================
        print("\n" + "="*80)
        print("FINAL SUMMARY")
        print("="*80)
        print("✅ Authentication: COMPLETE")
        print("✅ Profile Completion: COMPLETE")
        print("✅ Assessment Navigation: COMPLETE")
        print("\n🎉 Complete flow test PASSED!")
        print("="*80)
        
        # Keep browser open for inspection
        print("\n⏸️  Browser will remain open for 60 seconds for manual inspection...")
        print("   Press Ctrl+C to close early\n")
        time.sleep(60)
        
    except KeyboardInterrupt:
        print("\n\n⚠️  Test interrupted by user")
    except Exception as e:
        print(f"\n\n❌ Error during test: {e}")
        import traceback
        traceback.print_exc()
        
        # Take screenshot on failure
        try:
            screenshot_path = project_root / "reports" / "screenshots" / f"error_{int(time.time())}.png"
            driver.save_screenshot(str(screenshot_path))
            print(f"\n📸 Screenshot saved to: {screenshot_path}")
        except:
            pass
    finally:
        if driver:
            driver.quit()
            print("\n✅ Browser closed")


if __name__ == "__main__":
    test_complete_flow()

