"""
Component Test: Login Functionality

Tests login component in isolation with comprehensive error handling.
"""
import pytest
from pages.login_page import LoginPage
from config.config import TEST_USERNAME, TEST_PASSWORD, TEST_NEW_PASSWORD, BASE_URL
from utils.password_tracker import password_tracker


@pytest.mark.component
@pytest.mark.login
class TestLoginComponent:
    """Component tests for login functionality"""
    
    def test_login_form_loads(self, driver):
        """Test that login form loads correctly"""
        login_page = LoginPage(driver)
        login_page.navigate()
        
        # Verify all form elements are present
        assert login_page.is_element_visible(login_page.IDENTIFIER_INPUT, timeout=5), \
               "Identifier input should be visible"
        assert login_page.is_element_visible(login_page.PASSWORD_INPUT, timeout=5), \
               "Password input should be visible"
        assert login_page.is_element_visible(login_page.SUBMIT_BUTTON, timeout=5), \
               "Submit button should be visible"
        
        print("✅ Login form loads correctly")
    
    def test_login_with_tracked_password(self, driver):
        """Test login using password tracker"""
        login_page = LoginPage(driver)
        
        # Get password from tracker (should use TEST_PASSWORD if not tracked)
        current_password = password_tracker.get_password(TEST_USERNAME, TEST_PASSWORD)
        
        # Login with tracked password
        login_page.login(identifier=TEST_USERNAME, password=current_password)
        
        # Verify navigation away from login page
        current_url = driver.current_url
        assert current_url.rstrip("/") != BASE_URL.rstrip("/") and "login" not in current_url.lower(), \
               f"Should navigate away from login page. Current URL: {current_url}"
        
        print(f"✅ Login successful with tracked password")
    
    def test_login_smart_fallback(self, driver):
        """Test smart password fallback mechanism"""
        login_page = LoginPage(driver)
        
        # Use smart login (password=None triggers fallback)
        login_page.login(identifier=TEST_USERNAME, password=None)
        
        # Verify navigation
        current_url = driver.current_url
        assert "/dashboard" in current_url or "/student" in current_url or "mandatory_reset" in driver.page_source.lower(), \
               f"Should navigate to dashboard or show password reset. Current URL: {current_url}"
        
        print("✅ Smart login fallback works correctly")
    
    def test_login_invalid_credentials(self, driver):
        """Test login with invalid credentials shows error"""
        login_page = LoginPage(driver)
        login_page.navigate()
        
        # Enter invalid credentials
        login_page.enter_identifier("INVALID_CPID")
        login_page.enter_password("INVALID_PASSWORD")
        login_page.click_submit()
        
        # Wait for error toast
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.webdriver.common.by import By
        from config.config import MEDIUM_WAIT
        
        try:
            error_toast = WebDriverWait(driver, MEDIUM_WAIT).until(
                EC.presence_of_element_located((By.XPATH, 
                    "//div[@role='status' and @aria-live='polite' and (contains(text(), 'Invalid') or contains(text(), 'not found'))]"))
            )
            assert error_toast.is_displayed(), "Error toast should be visible"
            print(f"✅ Error toast appeared: {error_toast.text[:50]}")
        except Exception as e:
            # Fallback: check page source
            assert "Invalid" in driver.page_source or "not found" in driver.page_source.lower(), \
                   f"Error message should be present. Error: {e}"
            print("✅ Error message found in page source")
        
        # Verify still on login page
        assert "/login" in driver.current_url or driver.current_url.rstrip("/") == BASE_URL.rstrip("/"), \
               "Should remain on login page after invalid credentials"
        
        print("✅ Invalid credentials handled correctly")


