"""
Pytest Configuration for Student Assessment Tests

Includes smart fixtures for assessment flow:
- Smart login with optimized waits
- Password reset handling (if needed)
- Profile completion handling (if needed)
- Navigation to assessment page
"""
import pytest
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 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


@pytest.fixture(scope="function")
def smart_assessment_setup(driver):
    """
    World-class smart fixture to reach assessment page.
    
    This fixture:
    1. Logs in with smart password handling
    2. Resets password if needed (only if not already reset)
    3. Completes profile if needed (only if not already complete)
    4. Navigates to assessment page
    
    Optimizations:
    - Uses smart wait optimizer to skip unnecessary modal checks
    - Only handles modals if they're actually present
    - Fast detection using robust locators
    - Animation-aware waits
    
    Returns:
        dict: Contains page objects and student info
    """
    # Load student data
    try:
        student_data_manager.load_students_from_csv()
    except:
        pass
    
    # Get first student (or can be configured)
    students = student_data_manager._students
    if not students:
        pytest.skip("No student data loaded from CSV")
    
    cpid = list(students.keys())[0]
    student_data = students[cpid]
    
    print(f"\n🚀 Smart Assessment Setup for: {cpid}")
    print(f"   Name: {student_data.get('first_name')} {student_data.get('last_name')}")
    
    # Step 1: Smart Login
    login_page = LoginPage(driver)
    
    # Determine which password to use
    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 with smart password handling
    login_page.login(identifier=cpid, password=password_to_use)
    
    # Get the password that was actually used (for smart wait)
    actual_password_used = tracked_password if tracked_password != student_data.get('password') else TEST_NEW_PASSWORD
    
    # Step 2: Smart Wait for Dashboard (with optimizations)
    SmartWaitOptimizer.smart_wait_for_dashboard(driver, cpid, actual_password_used)
    
    # Step 3: Handle Password Reset (only if needed)
    reset_page = MandatoryResetPage(driver)
    
    # Smart check: Only check if password wasn't already reset
    if SmartWaitOptimizer.should_check_password_reset(cpid, actual_password_used):
        if reset_page.is_modal_present():
            print("✅ Password reset modal detected - resetting password")
            current_password = password_tracker.get_password(cpid, student_data.get('password'))
            reset_page.reset_password(
                current_password=current_password,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD,
                student_cpid=cpid
            )
            print("✅ Password reset completed")
            # Wait for modal to close (animation)
            time.sleep(SmartWaitOptimizer.ANIMATION_NORMAL + SmartWaitOptimizer.SAFETY_PADDING)
        else:
            print("⚡ Password reset modal not present (already reset)")
    else:
        print("⚡ Skipping password reset check (password already reset)")
    
    # Step 4: Handle Profile Incomplete (only if needed)
    profile_incomplete = ProfileIncompletePage(driver)
    
    # Smart check: Only check if profile might be incomplete
    if SmartWaitOptimizer.should_check_profile_incomplete(driver):
        if profile_incomplete.is_modal_present():
            print("✅ Profile incomplete modal detected - completing profile")
            profile_incomplete.click_complete()
            # Wait for navigation (animation)
            time.sleep(SmartWaitOptimizer.ANIMATION_NORMAL + SmartWaitOptimizer.SAFETY_PADDING)
            
            # Complete profile to 100%
            profile_editor = ProfileEditorPage(driver)
            profile_editor.wait_for_page_load()
            profile_editor.complete_profile_to_100(student_cpid=cpid)
            print("✅ Profile completed to 100%")
            
            # Wait for navigation back to dashboard
            time.sleep(SmartWaitOptimizer.ANIMATION_NORMAL + SmartWaitOptimizer.SAFETY_PADDING)
        else:
            print("⚡ Profile incomplete modal not present (profile already complete)")
    else:
        print("⚡ Skipping profile incomplete check (profile already complete)")
    
    # Step 5: Navigate to Assessment Page
    from pages.assessments_page import AssessmentsPage
    assessments_page = AssessmentsPage(driver)
    assessments_page.navigate()
    assessments_page.wait_for_page_load()
    
    print("✅ Smart assessment setup completed - ready for assessment tests")
    
    return {
        'driver': driver,
        'cpid': cpid,
        'student_data': student_data,
        'login_page': login_page,
        'assessments_page': assessments_page,
    }
