#!/usr/bin/env python3
"""
Performance Test for Client Popup Optimization

This script tests the performance improvement of the optimized client_popup view.
"""

import os
import sys
import django
import time
from datetime import datetime

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import Client
from django.contrib.auth import get_user_model
from users.models import CustomUser

def test_client_popup_performance():
    """Test the performance of client popup loading"""
    
    print("=" * 60)
    print("CLIENT POPUP PERFORMANCE TEST")
    print("=" * 60)
    
    # Get a test client
    try:
        test_client = CustomUser.objects.filter(role='borrower').first()
        if not test_client:
            print("❌ No test clients found. Please create some test clients first.")
            return
        
        print(f"✅ Testing with client: {test_client.get_full_name()} (ID: {test_client.id})")
        
        # Create a test user for authentication
        User = get_user_model()
        test_user = User.objects.filter(is_staff=True).first()
        if not test_user:
            print("❌ No staff users found. Please create a staff user first.")
            return
        
        # Create Django test client
        client = Client()
        client.force_login(test_user)
        
        # Test URL
        url = f'/users/clients/{test_client.id}/popup/'
        
        print(f"\n🔗 Testing URL: {url}")
        print(f"⏰ Starting performance test at: {datetime.now().strftime('%H:%M:%S')}")
        
        # Test multiple requests to measure performance
        times = []
        for i in range(5):
            start_time = time.time()
            
            response = client.get(url)
            
            end_time = time.time()
            duration = end_time - start_time
            times.append(duration)
            
            print(f"  Request {i+1}: {duration:.3f}s (Status: {response.status_code})")
            
            # Small delay between requests
            time.sleep(0.5)
        
        # Calculate statistics
        avg_time = sum(times) / len(times)
        min_time = min(times)
        max_time = max(times)
        
        print(f"\n📊 PERFORMANCE RESULTS:")
        print(f"  Average time: {avg_time:.3f}s")
        print(f"  Minimum time: {min_time:.3f}s")
        print(f"  Maximum time: {max_time:.3f}s")
        
        # Performance assessment
        if avg_time < 0.5:
            print(f"  🚀 EXCELLENT: Very fast response time!")
        elif avg_time < 1.0:
            print(f"  ✅ GOOD: Acceptable response time")
        elif avg_time < 2.0:
            print(f"  ⚠️  MODERATE: Response time could be improved")
        else:
            print(f"  ❌ SLOW: Response time needs optimization")
        
        # Test cache effectiveness
        print(f"\n🧪 TESTING CACHE EFFECTIVENESS:")
        
        # First request (should be slow)
        start_time = time.time()
        response1 = client.get(url)
        first_request_time = time.time() - start_time
        
        # Second request (should be fast due to cache)
        start_time = time.time()
        response2 = client.get(url)
        second_request_time = time.time() - start_time
        
        print(f"  First request: {first_request_time:.3f}s")
        print(f"  Second request: {second_request_time:.3f}s")
        
        if second_request_time < first_request_time * 0.5:
            print(f"  ✅ Cache is working effectively!")
        else:
            print(f"  ⚠️  Cache may not be working optimally")
        
        print(f"\n✅ Performance test completed at: {datetime.now().strftime('%H:%M:%S')}")
        
    except Exception as e:
        print(f"❌ Error during performance test: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_client_popup_performance()
