"""
Profile Filling Test Cases

Tests complete profile filling functionality for new students.
"""
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 config.config import TEST_NEW_PASSWORD, BASE_URL
import time


class TestProfileFilling:
    """Test cases for profile filling functionality"""
    
    def test_profile_incomplete_modal_appears(self, driver, new_student_credentials):
        """Test that profile incomplete modal appears for incomplete profiles"""
        cpid, _ = new_student_credentials
        
        # Login using smart login (handles password automatically)
        login_page = LoginPage(driver)
        login_page.login(identifier=cpid, password=None)  # Smart login handles password
        
        # Handle password reset if needed
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            # Get current password from tracker or use Excel password
            from utils.password_tracker import password_tracker
            from config.config import TEST_PASSWORD
            current_password = password_tracker.get_password(cpid, TEST_PASSWORD)
            reset_page.reset_password(
                current_password=current_password,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD,
                student_cpid=cpid
            )
        
        # 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 found - Progress: {progress}")
            assert progress != "100%", "Profile should be incomplete"
        else:
            print("⚠️  Profile incomplete modal not found - profile may already be complete")
    
    def test_navigate_to_profile_editor(self, driver, new_student_credentials):
        """Test navigation to profile editor from incomplete modal"""
        cpid, _ = new_student_credentials
        
        # Login using smart login (handles password automatically)
        login_page = LoginPage(driver)
        login_page.login(identifier=cpid, password=None)  # Smart login handles password
        
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            # Get current password from tracker or use Excel password
            from utils.password_tracker import password_tracker
            from config.config import TEST_PASSWORD
            current_password = password_tracker.get_password(cpid, TEST_PASSWORD)
            reset_page.reset_password(
                current_password=current_password,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD,
                student_cpid=cpid
            )
        
        # Click complete profile button
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            profile_incomplete.click_complete()
            
            # Verify navigation to profile editor
            assert "/profile-builder" in driver.current_url, \
                   "Should navigate to profile editor"
            print("✅ Successfully navigated to profile editor")
        else:
            pytest.skip("Profile incomplete modal not present")
    
    def test_profile_editor_page_loads(self, driver, new_student_credentials):
        """Test that profile editor page loads correctly"""
        cpid, _ = new_student_credentials
        
        # Login using smart login (handles password automatically)
        login_page = LoginPage(driver)
        login_page.login(identifier=cpid, password=None)  # Smart login handles password
        
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            # Get current password from tracker or use Excel password
            from utils.password_tracker import password_tracker
            from config.config import TEST_PASSWORD
            current_password = password_tracker.get_password(cpid, TEST_PASSWORD)
            reset_page.reset_password(
                current_password=current_password,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD,
                student_cpid=cpid
            )
        
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            profile_incomplete.click_complete()
            time.sleep(2)  # Wait for navigation
        
        # Navigate to profile editor
        profile_editor = ProfileEditorPage(driver)
        profile_editor.navigate()  # Navigate first
        profile_editor.wait_for_page_load()  # Then wait for load
        
        # Check for profile editor elements (PAGE might not have data-testid, so check for progress or tabs)
        page_loaded = False
        try:
            page_loaded = profile_editor.is_element_visible(profile_editor.PAGE, timeout=3)
        except:
            pass
        
        if not page_loaded:
            # Fallback: check for progress value or tabs
            try:
                page_loaded = profile_editor.is_element_visible(profile_editor.PROGRESS_VALUE, timeout=3)
            except:
                try:
                    page_loaded = profile_editor.is_element_visible(profile_editor.TAB_PERSONAL_INFORMATION, timeout=3)
                except:
                    pass
        
        assert page_loaded or "/profile-builder" in driver.current_url, \
               f"Profile editor page should be visible. URL: {driver.current_url}"
        
        progress = profile_editor.get_progress_value()
        print(f"✅ Profile editor loaded - Current progress: {progress}")
    
    def test_profile_all_tabs_accessible(self, driver, new_student_credentials):
        """Test that all profile tabs are accessible"""
        cpid, _ = new_student_credentials
        
        # Login using smart login (handles password automatically)
        login_page = LoginPage(driver)
        login_page.login(identifier=cpid, password=None)  # Smart login handles password
        
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            # Get current password from tracker or use Excel password
            from utils.password_tracker import password_tracker
            from config.config import TEST_PASSWORD
            current_password = password_tracker.get_password(cpid, TEST_PASSWORD)
            reset_page.reset_password(
                current_password=current_password,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD,
                student_cpid=cpid
            )
        
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            profile_incomplete.click_complete()
            time.sleep(2)  # Wait for navigation
        
        # Navigate to profile editor
        profile_editor = ProfileEditorPage(driver)
        profile_editor.navigate()  # Navigate first
        profile_editor.wait_for_page_load()  # Then wait for load
        
        # Test accessing each tab (CORRECT STRUCTURE: 8 tabs, 0-7)
        # Note: Contact Information is merged into Personal Information tab
        tabs = [
            ("Personal Information", profile_editor.TAB_PERSONAL_INFORMATION),  # Tab 0 (includes Contact Info)
            ("Parent/Guardian Information", profile_editor.TAB_PARENT_GUARDIAN_INFORMATION),  # Tab 1
            ("Institution Details", profile_editor.TAB_INSTITUTION_DETAILS),  # Tab 2
            ("Focus Areas", profile_editor.TAB_FOCUS_AREAS),  # Tab 3
            ("Self-Assessment", profile_editor.TAB_SELF_ASSESSMENT),  # Tab 4
            ("Hobbies & Clubs", profile_editor.TAB_HOBBIES_CLUBS),  # Tab 5
            ("Achievements", profile_editor.TAB_ACHIEVEMENTS),  # Tab 6
            ("Expectations", profile_editor.TAB_EXPECTATIONS),  # Tab 7
        ]
        
        for i, (tab_name, tab_locator) in enumerate(tabs):
            try:
                profile_editor.navigate_to_tab(i)
                time.sleep(0.5)  # Wait for tab to load
                print(f"  ✅ Tab accessible: {tab_name} (Tab {i+1}/8)")
            except Exception as e:
                print(f"  ⚠️  Tab not accessible: {tab_name} - {e}")
        
        print("✅ All tabs accessibility test completed")
    
    def test_profile_completion_with_data(self, driver, new_student_credentials):
        """
        Test complete profile completion to 100% by filling all 8 tabs
        
        NEW STRUCTURE (8 tabs - UI Dev Team Updated):
        1. Personal Information (includes BOTH Personal Info AND Contact Information)
        2. Parent/Guardian Information
        3. Institution Details
        4. Focus Areas
        5. Self-Assessment
        6. Hobbies & Clubs
        7. Achievements
        8. Expectations
        
        This test:
        1. Logs in and handles password reset/profile incomplete modals
        2. Navigates through all 8 tabs (handling horizontal scroll)
        3. Fills all required and important optional fields
        4. Verifies progress reaches 100%
        5. Saves successfully
        """
        cpid, _ = new_student_credentials
        
        # Login using smart login (handles password automatically)
        login_page = LoginPage(driver)
        login_page.login(identifier=cpid, password=None)  # Smart login handles password
        
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            # Get current password from tracker or use Excel password
            from utils.password_tracker import password_tracker
            from config.config import TEST_PASSWORD, TEST_NEW_PASSWORD
            current_password = password_tracker.get_password(cpid, TEST_PASSWORD)
            reset_page.reset_password(
                current_password=current_password,
                new_password=TEST_NEW_PASSWORD,
                confirm_password=TEST_NEW_PASSWORD,
                student_cpid=cpid
            )
        
        # Handle profile incomplete modal
        profile_incomplete = ProfileIncompletePage(driver)
        if profile_incomplete.is_modal_present():
            profile_incomplete.click_complete()
            time.sleep(2)  # Wait for navigation after clicking complete
        
        # Navigate to profile editor
        profile_editor = ProfileEditorPage(driver)
        profile_editor.navigate()  # Navigate first
        profile_editor.wait_for_page_load()  # Then wait for load
        
        # Get initial progress
        initial_progress = profile_editor.get_progress_value()
        print(f"📊 Initial profile progress: {initial_progress}")
        
        # Complete profile to 100% using student data from CSV (prevents age verification modal)
        # Pass student CPID to use correct DOB that matches school records
        success = profile_editor.complete_profile_to_100(student_cpid=cpid)
        
        # Verify progress reached 100%
        final_progress = profile_editor.get_progress_value()
        print(f"📊 Final profile progress: {final_progress}")
        
        assert "100%" in final_progress or final_progress == "100", \
               f"Profile should be 100% complete. Current: {final_progress}"
        assert success, "Profile completion method should return True"
        
        print("✅ Profile completed to 100% successfully!")


@pytest.fixture
def new_student_credentials():
    """Fixture providing new student credentials from config"""
    from config.config import TEST_USERNAME, TEST_PASSWORD
    return (TEST_USERNAME, TEST_PASSWORD)


@pytest.fixture
def new_student_with_data():
    """Fixture providing new student with complete data"""
    # TODO: Get from Excel file with all profile data
    student_data = {
        "first_name": "Test",
        "last_name": "Student",
        "gender": "Male",
        "dob": "2000-01-01",
        "language": "English",
        "student_id": "1234567890",
        
    }
    return ("NEW_STUDENT_CPID", "DEFAULT_PASSWORD", student_data)

