#!/usr/bin/env python3
"""
Comprehensive test script for SweetAlert login messages functionality.
This script tests various login scenarios and validates message display.
"""

import requests
import re
from bs4 import BeautifulSoup
import json

class LoginTester:
    def __init__(self, base_url="http://localhost:8090"):
        self.base_url = base_url
        self.login_url = f"{base_url}/auth/login"
        self.session = requests.Session()
        
    def get_csrf_token(self, url):
        """Extract CSRF token from form"""
        try:
            response = self.session.get(url)
            soup = BeautifulSoup(response.content, 'html.parser')
            csrf_token = soup.find('input', {'name': 'csrfmiddlewaretoken'})
            return csrf_token.get('value') if csrf_token else None
        except Exception as e:
            print(f"   ❌ Error getting CSRF token: {e}")
            return None
    
    def check_sweetalert_integration(self):
        """Check if SweetAlert is properly loaded"""
        print("🔍 Checking SweetAlert Integration...")
        
        try:
            response = self.session.get(self.login_url)
            content = response.text
            
            # Check for SweetAlert CSS and JS
            has_sweetalert_css = 'sweetalert2' in content
            has_sweetalert_js = 'Swal.fire' in content or 'sweetalert2' in content
            has_message_handler = 'messages.forEach' in content or 'messageElements' in content
            
            print(f"   SweetAlert CSS: {'✅' if has_sweetalert_css else '❌'}")
            print(f"   SweetAlert JS: {'✅' if has_sweetalert_js else '❌'}")
            print(f"   Message Handler: {'✅' if has_message_handler else '❌'}")
            
            if has_sweetalert_css and has_sweetalert_js and has_message_handler:
                print("   ✅ SweetAlert integration is properly configured!")
                return True
            else:
                print("   ❌ SweetAlert integration has issues")
                return False
                
        except Exception as e:
            print(f"   ❌ Error checking SweetAlert: {e}")
            return False
    
    def test_form_validation_errors(self):
        """Test client-side and server-side form validation"""
        print("\n📝 Testing Form Validation Errors...")
        
        test_cases = [
            {
                'name': 'Empty email',
                'data': {'email': '', 'password': 'test123'},
                'expected': 'Required field validation'
            },
            {
                'name': 'Invalid email format',
                'data': {'email': 'invalid-email', 'password': 'test123'},
                'expected': 'Email format validation'
            },
            {
                'name': 'Invalid credentials',
                'data': {'email': 'nonexistent@test.com', 'password': 'wrongpass'},
                'expected': 'Authentication error'
            }
        ]
        
        for test_case in test_cases:
            print(f"\n   🧪 Testing: {test_case['name']}")
            csrf_token = self.get_csrf_token(self.login_url)
            
            if csrf_token:
                data = test_case['data'].copy()
                data['csrfmiddlewaretoken'] = csrf_token
                
                response = self.session.post(self.login_url, data=data, allow_redirects=False)
                print(f"      Status: {response.status_code}")
                print(f"      Expected: {test_case['expected']}")
                
                if response.status_code == 200:
                    print("      ✅ Form returned with validation errors (as expected)")
                elif response.status_code == 302:
                    print("      ❌ Unexpected redirect - check validation logic")
                else:
                    print(f"      ❓ Unexpected status: {response.status_code}")
            else:
                print("      ❌ Could not get CSRF token")
    
    def test_successful_login(self):
        """Test successful login with valid credentials"""
        print("\n✅ Testing Successful Login...")
        
        csrf_token = self.get_csrf_token(self.login_url)
        if csrf_token:
            login_data = {
                'email': 'test@adtlas.com',
                'password': 'testpass123',
                'remember_me': True,
                'csrfmiddlewaretoken': csrf_token
            }
            
            response = self.session.post(self.login_url, data=login_data, allow_redirects=False)
            print(f"   Status: {response.status_code}")
            
            if response.status_code == 302:
                redirect_location = response.headers.get('Location', '')
                print(f"   Redirect to: {redirect_location}")
                
                if 'dashboard' in redirect_location or redirect_location == '/':
                    print("   ✅ Successful login with proper redirect!")
                    
                    # Follow redirect to see success message
                    dashboard_response = self.session.get(f"{self.base_url}{redirect_location}")
                    if 'Welcome back' in dashboard_response.text:
                        print("   ✅ Success message should be displayed via SweetAlert!")
                    
                    return True
                else:
                    print(f"   ❓ Unexpected redirect location: {redirect_location}")
            else:
                print("   ❌ Login failed - check credentials or form logic")
                
        return False
    
    def validate_sweetalert_configuration(self):
        """Validate SweetAlert configuration and message handling"""
        print("\n⚙️ Validating SweetAlert Configuration...")
        
        response = self.session.get(self.login_url)
        content = response.text
        
        # Check for proper SweetAlert configuration
        config_checks = {
            'SweetAlert Library': 'sweetalert2' in content.lower(),
            'Message Array Creation': 'messages' in content and 'forEach' in content,
            'Toast Position': 'top-end' in content,
            'Timer Configuration': 'timer:' in content,
            'Progress Bar': 'timerProgressBar' in content,
            'Close Button': 'showCloseButton' in content,
            'Mouse Events': 'mouseenter' in content and 'mouseleave' in content,
        }
        
        for check, passed in config_checks.items():
            print(f"   {check}: {'✅' if passed else '❌'}")
        
        all_passed = all(config_checks.values())
        if all_passed:
            print("   ✅ All SweetAlert configurations are correct!")
        else:
            print("   ❌ Some SweetAlert configurations need attention")
        
        return all_passed
    
    def run_comprehensive_test(self):
        """Run all tests and provide summary"""
        print("🧪 COMPREHENSIVE SWEETALERT LOGIN TESTING")
        print("=" * 60)
        
        # Test 1: Check SweetAlert Integration
        sweetalert_ok = self.check_sweetalert_integration()
        
        # Test 2: Validate Configuration
        config_ok = self.validate_sweetalert_configuration()
        
        # Test 3: Test Form Validation
        self.test_form_validation_errors()
        
        # Test 4: Test Successful Login
        login_ok = self.test_successful_login()
        
        # Summary
        print("\n📊 TEST SUMMARY")
        print("=" * 30)
        print(f"SweetAlert Integration: {'✅ PASS' if sweetalert_ok else '❌ FAIL'}")
        print(f"Configuration: {'✅ PASS' if config_ok else '❌ FAIL'}")
        print(f"Successful Login: {'✅ PASS' if login_ok else '❌ FAIL'}")
        
        if sweetalert_ok and config_ok:
            print("\n🎉 SweetAlert messages are properly configured!")
            print("\n📝 What's Working:")
            print("   ✅ SweetAlert2 library is loaded")
            print("   ✅ Django messages are converted to SweetAlert toasts")
            print("   ✅ Messages appear in top-right corner")
            print("   ✅ Toast configuration with timer and progress bar")
            print("   ✅ Mouse hover pauses timer")
            print("   ✅ Form validation errors display correctly")
            
            print("\n🎯 To Test Manually:")
            print("   1. Go to http://localhost:8090/auth/login")
            print("   2. Try invalid credentials - see error toast")
            print("   3. Use valid credentials: test@adtlas.com / testpass123")
            print("   4. See success message as SweetAlert toast")
            
        else:
            print("\n❌ Issues found that need attention:")
            if not sweetalert_ok:
                print("   - SweetAlert integration needs fixing")
            if not config_ok:
                print("   - SweetAlert configuration needs adjustment")

if __name__ == "__main__":
    tester = LoginTester()
    tester.run_comprehensive_test()
