#!/usr/bin/env python3
"""
Test Single Student Flow

Quick test script to verify the complete flow works for a single student.
"""
import sys
import time
from pathlib import Path

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 utils.driver_manager import DriverManager
from config.config import BASE_URL, TEST_NEW_PASSWORD


def test_student_flow(cpid, password, headless=False):
    """
    Test complete flow for a single student
    
    Args:
        cpid: Student CPID
        password: Student password
        headless: Run in headless mode
    """
    driver = None
    try:
        print(f"\n{'='*80}")
        print(f"TESTING STUDENT: {cpid}")
        print(f"{'='*80}\n")
        
        # Initialize driver
        driver_manager = DriverManager()
        driver = driver_manager.get_driver(headless=headless)
        
        # Step 1: Login
        print("[STEP 1] Logging in...")
        login_page = LoginPage(driver)
        login_page.login(identifier=cpid, password=password)
        time.sleep(2)
        print(f"  ✅ Logged in successfully")
        print(f"  Current URL: {driver.current_url}")
        
        # Step 2: Handle Password Reset
        print("\n[STEP 2] Checking for Password Reset...")
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            print("  ✅ Password reset modal found")
            print("  Automatically handling password reset...")
            reset_page.reset_password(
                current_password=password,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD
            )
            print("  ✅ Password reset completed")
            password = TEST_NEW_PASSWORD  # Update for future use
        else:
            print("  ✅ No password reset required")
        
        # Step 3: Handle Profile Incomplete Modal
        print("\n[STEP 3] Checking for Profile Incomplete Modal...")
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            progress = profile_incomplete.get_progress_value()
            print(f"  Profile incomplete - Current Progress: {progress}")
            print("  Clicking Complete Profile button...")
            profile_incomplete.click_complete()
            time.sleep(3)
            print(f"  Navigated to: {driver.current_url}")
        else:
            print("  ✅ Profile already complete or modal not present")
        
        # Step 4: Check Profile Editor (only if profile incomplete modal was shown)
        print("\n[STEP 4] Checking Profile Status...")
        try:
            # Try to navigate to profile editor to check status
            from pages.student_nav_page import StudentNavPage
            nav = StudentNavPage(driver)
            # Check if we can access profile editor
            current_url = driver.current_url
            if "/profile" in current_url or "/dashboard" in current_url:
                print(f"  Current URL: {current_url}")
                print("  ✅ Successfully logged in and navigated")
                print("  Note: Profile status can be checked from dashboard")
        except Exception as e:
            print(f"  ⚠️  Could not check profile editor: {e}")
            print("  But login was successful!")
        
        print(f"\n{'='*80}")
        print("TEST COMPLETED SUCCESSFULLY")
        print(f"{'='*80}\n")
        
        # Keep browser open for inspection if not headless
        if not headless:
            print("Keeping browser open for 30 seconds for inspection...")
            time.sleep(30)
        
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
    finally:
        if driver:
            driver.quit()


def main():
    """Main entry point"""
    import argparse
    
    parser = argparse.ArgumentParser(description='Test single student flow')
    parser.add_argument('--cpid', type=str, required=True, help='Student CPID')
    parser.add_argument('--password', type=str, required=True, help='Student password')
    parser.add_argument('--headless', action='store_true', help='Run in headless mode')
    
    args = parser.parse_args()
    
    test_student_flow(args.cpid, args.password, headless=args.headless)


if __name__ == "__main__":
    main()

