"""
Login Test Cases

Tests login functionality with various scenarios.
"""
import pytest
from pages.login_page import LoginPage
from pages.mandatory_reset_page import MandatoryResetPage
from pages.dashboard_page import DashboardPage
from config.config import TEST_USERNAME, TEST_PASSWORD, BASE_URL


@pytest.mark.authentication
@pytest.mark.login
class TestLogin:
    """Test cases for login functionality"""
    
    def test_login_success(self, driver):
        """Test successful login with smart password handling"""
        login_page = LoginPage(driver)
        
        # Use smart login (password=None will use password_tracker and try fallback if needed)
        # The login method handles everything internally - password fallback, navigation, etc.
        login_page.login(identifier=TEST_USERNAME, password=None)
        
        # Verify we're not on login page anymore (login method handles navigation and fallback)
        current_url = driver.current_url
        # Should be on dashboard, student page, or password reset modal (not on login page)
        assert current_url.rstrip("/") != "http://localhost:3983" and "login" not in current_url.lower(), \
               f"Login should navigate away from login page. Current URL: {current_url}"
        
        # Should be on dashboard, student page, or password reset modal
        assert "/dashboard" in current_url or "/student" in current_url or "mandatory_reset" in driver.page_source.lower(), \
               f"Should be on dashboard or password reset. Current URL: {current_url}"
        
        print("✅ Login successful!")
    
    def test_login_with_invalid_credentials(self, driver):
        """Test login with invalid credentials"""
        login_page = LoginPage(driver)
        login_page.navigate()
        
        # Try to login with invalid credentials
        login_page.enter_identifier("INVALID_CPID")
        login_page.enter_password("INVALID_PASSWORD")
        
        # Click submit and immediately wait for toast (don't wait for anything else)
        login_page.click_submit()
        
        # Wait for error toast to appear - toast appears immediately after submit
        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
        
        # Wait for toast notification - appears immediately after API response
        # Toast has: role="status" aria-live="polite" and contains error text
        try:
            # Wait for toast with proper attributes
            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') or contains(text(), 'User not found'))]"))
            )
            # Verify it's visible
            assert error_toast.is_displayed(), "Error toast should be visible"
            error_text = error_toast.text
            print(f"✅ Error toast notification appeared: {error_text}")
        except Exception as e:
            # Fallback: check page source for error message
            WebDriverWait(driver, 2).until(
                lambda d: "Invalid" in d.page_source or "not found" in d.page_source.lower() or "User not found" in d.page_source
            )
            page_source = driver.page_source
            if "User not found" in page_source:
                error_text = "User not found"
            elif "Invalid username or password" in page_source:
                error_text = "Invalid username or password"
            else:
                error_text = "Login error"
            print(f"✅ Error message found in page source: {error_text}")
        
        # Verify error message
        assert "Invalid" in error_text or "not found" in error_text.lower() or "User not found" in error_text, \
               f"Error message should indicate login failure, got: {error_text}"
        
        # Verify we're still on login page
        assert "/login" in driver.current_url or driver.current_url.rstrip("/") == login_page.url.rstrip("/"), \
               "Should remain on login page after invalid credentials"
        
        print(f"✅ Error message verified: {error_text}")
    
    def test_login_with_remember_me(self, driver):
        """
        Test login with remember me checkbox checked
        
        IMPORTANT: "Remember me" only works within the same browser session.
        Each test gets a fresh browser, so this test verifies the checkbox
        functionality, not cross-session persistence.
        
        Uses smart login mechanism (tries Excel password, then Admin@123).
        """
        login_page = LoginPage(driver)
        
        # Use smart login with remember_me=True
        # The login method handles password fallback automatically
        login_page.login(identifier=TEST_USERNAME, password=None, remember_me=True)
        
        # Verify we're not on login page anymore
        current_url = driver.current_url
        assert current_url.rstrip("/") != "http://localhost:3983" and "login" not in current_url.lower(), \
               f"Login should navigate away from login page. Current URL: {current_url}"
        
        # Should be on dashboard, student page, or password reset modal
        assert "/dashboard" in current_url or "/student" in current_url or "mandatory_reset" in driver.page_source.lower(), \
               f"Should be on dashboard or password reset. Current URL: {current_url}"
        
        print("✅ Login with remember me successful!")
    
    def test_login_form_elements_visible(self, driver):
        """Test that all login form elements are visible"""
        login_page = LoginPage(driver)
        login_page.navigate()
        
        # Verify form elements are present (using data-testid - implemented ✅)
        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("✅ All login form elements are visible")
