#!/usr/bin/env python3
"""
Focused Profile Filling Test with Screenshots

Tests ONLY profile filling with screenshots at each step to identify:
1. What data is being added
2. What error toasts appear
3. Why progress might be stuck at 94%
"""
import sys
from pathlib import Path
import time
from datetime import datetime

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 TEST_NEW_PASSWORD, BASE_URL, TEST_USERNAME, TEST_PASSWORD


def take_screenshot(driver, step_name, tab_number):
    """Take screenshot and save with descriptive name"""
    screenshot_dir = project_root / "reports" / "screenshots" / "profile_filling"
    screenshot_dir.mkdir(parents=True, exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"tab_{tab_number}_{step_name}_{timestamp}.png"
    filepath = screenshot_dir / filename
    
    driver.save_screenshot(str(filepath))
    print(f"📸 Screenshot saved: {filepath.name}")
    return filepath


def test_profile_filling_with_screenshots():
    """Test profile filling with screenshots at each step"""
    driver = None
    try:
        print("="*80)
        print("🔍 FOCUSED PROFILE FILLING TEST WITH SCREENSHOTS")
        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()
        
        # Quick login
        print("\n📝 Quick Login...")
        login_page = LoginPage(driver)
        login_page.login(identifier=TEST_USERNAME, password=TEST_PASSWORD)
        time.sleep(2)
        
        # Handle password reset if needed
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            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)
        
        # Handle profile incomplete modal
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            progress = profile_incomplete.get_progress_value()
            print(f"⚠️  Profile incomplete modal - Progress: {progress}")
            profile_incomplete.click_complete()
            time.sleep(3)
        
        # Navigate to profile editor
        print("\n📝 Navigating to Profile Editor...")
        profile_editor = ProfileEditorPage(driver)
        profile_editor.navigate()
        profile_editor.wait_for_page_load()
        
        initial_progress = profile_editor.get_progress_value()
        print(f"📊 Initial Progress: {initial_progress}")
        take_screenshot(driver, "initial_state", 0)
        
        # ============================================================
        # TAB 1: Personal Information
        # ============================================================
        print("\n" + "="*80)
        print("TAB 1: Personal Information")
        print("="*80)
        profile_editor.navigate_to_tab(0)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 1)
        
        profile_editor.fill_personal_information(
            first_name="Test",
            last_name="Student",
            gender="Male",
            dob="2005-01-15",
            roll_number="12345",
            nationality="Indian",
            language="English",
            student_id="STU123456",
            specially_abled=False
        )
        time.sleep(1)
        take_screenshot(driver, "after_fill", 1)
        
        print("💾 Saving Tab 1...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 1: {progress}")
        take_screenshot(driver, "after_save", 1)
        
        # ============================================================
        # TAB 2: Contact Information
        # ============================================================
        print("\n" + "="*80)
        print("TAB 2: Contact Information")
        print("="*80)
        profile_editor.navigate_to_tab(1)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 2)
        
        profile_editor.fill_contact_information(
            email="test.student@example.com",
            phone="9876543210",
            address="123 Test Street, Test Area",
            city="Mumbai",
            state="Maharashtra",
            zip_code="400001",
            native_state="Maharashtra"
        )
        time.sleep(1)
        take_screenshot(driver, "after_fill", 2)
        
        print("💾 Saving Tab 2...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 2: {progress}")
        take_screenshot(driver, "after_save", 2)
        
        # ============================================================
        # TAB 3: Parent/Guardian
        # ============================================================
        print("\n" + "="*80)
        print("TAB 3: Parent/Guardian")
        print("="*80)
        profile_editor.navigate_to_tab(2)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 3)
        
        profile_editor.fill_parent_guardian(
            father_name="Father Test",
            father_age_range="41-50",
            father_occupation="Engineer",
            father_email="father@example.com",
            mother_name="Mother Test",
            mother_age_range="30-40",
            mother_occupation="Teacher",
            mother_email="mother@example.com",
            guardian_different=True,
            guardian_name="Guardian Test",
            guardian_relationship="Uncle",
            guardian_phone="9876543211",
            guardian_email="guardian@example.com",
            guardian_address="456 Guardian Street"
        )
        time.sleep(1)
        take_screenshot(driver, "after_fill", 3)
        
        print("💾 Saving Tab 3...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 3: {progress}")
        take_screenshot(driver, "after_save", 3)
        
        # ============================================================
        # TAB 4: Education Details
        # ============================================================
        print("\n" + "="*80)
        print("TAB 4: Education Details")
        print("="*80)
        profile_editor.navigate_to_tab(3)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 4)
        
        profile_editor.fill_education_details(
            full_name="Test Student",
            current_grade="10",
            section="A",
            board_stream="CBSE"
        )
        time.sleep(1)
        take_screenshot(driver, "after_fill", 4)
        
        print("💾 Saving Tab 4...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 4: {progress}")
        take_screenshot(driver, "after_save", 4)
        
        # ============================================================
        # TAB 5: Focus Areas
        # ============================================================
        print("\n" + "="*80)
        print("TAB 5: Focus Areas")
        print("="*80)
        profile_editor.navigate_to_tab(4)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 5)
        
        # Select short-term focus areas
        short_term = [
            profile_editor.SHORT_TERM_FOCUS_ACADEMICS,
            profile_editor.SHORT_TERM_FOCUS_FAMILY,
            profile_editor.SHORT_TERM_FOCUS_HEALTH
        ]
        for locator in short_term:
            checkbox = profile_editor.wait.wait_for_element_visible(locator)
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox)
            time.sleep(0.2)
            if not checkbox.is_selected():
                checkbox.click()
                driver.execute_script("arguments[0].dispatchEvent(new Event('change', { bubbles: true }));", checkbox)
                time.sleep(0.3)
        
        # Select long-term focus areas
        long_term = [
            profile_editor.LONG_TERM_FOCUS_ACADEMICS,
            profile_editor.LONG_TERM_FOCUS_FUTURE,
            profile_editor.LONG_TERM_FOCUS_PERSONAL_GROWTH
        ]
        for locator in long_term:
            checkbox = profile_editor.wait.wait_for_element_visible(locator)
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox)
            time.sleep(0.2)
            if not checkbox.is_selected():
                checkbox.click()
                driver.execute_script("arguments[0].dispatchEvent(new Event('change', { bubbles: true }));", checkbox)
                time.sleep(0.3)
        
        time.sleep(1)
        take_screenshot(driver, "after_fill", 5)
        
        print("💾 Saving Tab 5...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 5: {progress}")
        take_screenshot(driver, "after_save", 5)
        
        # ============================================================
        # TAB 6: Self-Assessment
        # ============================================================
        print("\n" + "="*80)
        print("TAB 6: Self-Assessment")
        print("="*80)
        profile_editor.navigate_to_tab(5)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 6)
        
        # Select strengths
        strengths = [
            profile_editor.STRENGTH_QUICK_LEARNING,
            profile_editor.STRENGTH_PROBLEM_SOLVING,
            profile_editor.STRENGTH_COMMUNICATION
        ]
        for locator in strengths:
            checkbox = profile_editor.wait.wait_for_element_visible(locator)
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox)
            time.sleep(0.2)
            if not checkbox.is_selected():
                checkbox.click()
                driver.execute_script("arguments[0].dispatchEvent(new Event('change', { bubbles: true }));", checkbox)
                time.sleep(0.3)
        
        # Select improvements
        improvements = [
            profile_editor.IMPROVEMENT_CURIOSITY,
            profile_editor.IMPROVEMENT_RISK_TAKING,
            profile_editor.IMPROVEMENT_LEADERSHIP
        ]
        for locator in improvements:
            checkbox = profile_editor.wait.wait_for_element_visible(locator)
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox)
            time.sleep(0.2)
            if not checkbox.is_selected():
                checkbox.click()
                driver.execute_script("arguments[0].dispatchEvent(new Event('change', { bubbles: true }));", checkbox)
                time.sleep(0.3)
        
        time.sleep(1)
        take_screenshot(driver, "after_fill", 6)
        
        print("💾 Saving Tab 6...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 6: {progress}")
        take_screenshot(driver, "after_save", 6)
        
        # ============================================================
        # TAB 7: Hobbies & Clubs
        # ============================================================
        print("\n" + "="*80)
        print("TAB 7: Hobbies & Clubs")
        print("="*80)
        profile_editor.navigate_to_tab(6)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 7)
        
        # Select hobbies
        hobbies = [
            profile_editor.HOBBY_READING,
            profile_editor.HOBBY_SPORTS,
            profile_editor.HOBBY_MUSICAL
        ]
        for locator in hobbies:
            checkbox = profile_editor.wait.wait_for_element_visible(locator)
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox)
            time.sleep(0.2)
            if not checkbox.is_selected():
                checkbox.click()
                driver.execute_script("arguments[0].dispatchEvent(new Event('change', { bubbles: true }));", checkbox)
                time.sleep(0.3)
        
        # Select clubs
        clubs = [
            profile_editor.CLUB_SCIENCE,
            profile_editor.CLUB_QUIZ,
            profile_editor.CLUB_LITERARY
        ]
        for locator in clubs:
            checkbox = profile_editor.wait.wait_for_element_visible(locator)
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox)
            time.sleep(0.2)
            if not checkbox.is_selected():
                checkbox.click()
                driver.execute_script("arguments[0].dispatchEvent(new Event('change', { bubbles: true }));", checkbox)
                time.sleep(0.3)
        
        time.sleep(1)
        take_screenshot(driver, "after_fill", 7)
        
        print("💾 Saving Tab 7...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 7: {progress}")
        take_screenshot(driver, "after_save", 7)
        
        # ============================================================
        # TAB 8: Achievements
        # ============================================================
        print("\n" + "="*80)
        print("TAB 8: Achievements")
        print("="*80)
        profile_editor.navigate_to_tab(7)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 8)
        
        # Calculate age for conditional trained field
        from datetime import datetime
        try:
            dob_date = datetime.strptime("2005-01-15", "%Y-%m-%d")
            current_date = datetime.now()
            age = current_date.year - dob_date.year - ((current_date.month, current_date.day) < (dob_date.month, dob_date.day))
            is_adult = 18 <= age <= 23
        except:
            is_adult = False
        
        profile_editor.fill_achievements(
            academics="School topper in 9th grade",
            sports="Won district level cricket tournament",
            cultural="Participated in school annual day",
            trained="Professional certification in Python programming" if is_adult else None,
            others="Volunteer work at local NGO"
        )
        time.sleep(1)
        take_screenshot(driver, "after_fill", 8)
        
        print("💾 Saving Tab 8...")
        profile_editor.click_save()
        time.sleep(2)
        progress = profile_editor.get_progress_value()
        print(f"📊 Progress after Tab 8: {progress}")
        take_screenshot(driver, "after_save", 8)
        
        # ============================================================
        # TAB 9: Expectations
        # ============================================================
        print("\n" + "="*80)
        print("TAB 9: Expectations")
        print("="*80)
        profile_editor.navigate_to_tab(8)
        time.sleep(1)
        take_screenshot(driver, "before_fill", 9)
        
        # Select expectations
        expectations = [
            profile_editor.EXPECTATION_SELF_UNDERSTANDING,
            profile_editor.EXPECTATION_CAREER_GUIDANCE,
            profile_editor.EXPECTATION_ACADEMIC_SUPPORT
        ]
        for locator in expectations:
            checkbox = profile_editor.wait.wait_for_element_visible(locator)
            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", checkbox)
            time.sleep(0.2)
            if not checkbox.is_selected():
                checkbox.click()
                driver.execute_script("arguments[0].dispatchEvent(new Event('change', { bubbles: true }));", checkbox)
                time.sleep(0.3)
        
        time.sleep(1)
        take_screenshot(driver, "after_fill", 9)
        
        print("💾 Saving Tab 9 (FINAL)...")
        profile_editor.click_save()
        time.sleep(3)  # Longer wait for final save
        progress = profile_editor.get_progress_value()
        print(f"📊 Final Progress after Tab 9: {progress}")
        take_screenshot(driver, "after_save_final", 9)
        
        # Wait for backend sync
        print("\n⏳ Waiting for backend to sync...")
        time.sleep(5)
        final_progress = profile_editor.get_progress_value()
        print(f"📊 Final Progress after sync: {final_progress}")
        take_screenshot(driver, "final_state", 9)
        
        print("\n" + "="*80)
        print("TEST COMPLETE")
        print("="*80)
        print(f"✅ Initial Progress: {initial_progress}")
        print(f"✅ Final Progress: {final_progress}")
        print(f"\n📸 Screenshots saved in: reports/screenshots/profile_filling/")
        print("="*80)
        
        # Keep browser open for inspection
        print("\n⏸️  Browser will remain open for 120 seconds for manual inspection...")
        time.sleep(120)
        
    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:
            take_screenshot(driver, "error", 0)
        except:
            pass
    finally:
        if driver:
            driver.quit()
            print("\n✅ Browser closed")


if __name__ == "__main__":
    test_profile_filling_with_screenshots()






