"""
Simple test to verify the client reports view works correctly
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
django.setup()

from django.test import RequestFactory
from django.contrib.auth.models import AnonymousUser
from users.models import CustomUser, Branch
from reports.views import borrower_reports
from reports.client_report_service import ClientReportService

def test_client_reports_view():
    """Test that the client reports view renders correctly"""
    print("Testing client reports view...")
    
    # Create a test user with admin role
    try:
        admin_user = CustomUser.objects.filter(role='admin', is_superuser=True).first()
        if not admin_user:
            print("❌ No admin user found in database")
            return False
        
        print(f"✓ Using admin user: {admin_user.username}")
        
        # Create request factory
        factory = RequestFactory()
        request = factory.get('/reports/borrowers/')
        request.user = admin_user
        request.session = {}
        
        # Mock the has_permission method
        def mock_has_permission(module, action):
            return True
        request.user.has_permission = mock_has_permission
        
        # Call the view
        response = borrower_reports(request)
        
        print(f"✓ View returned status code: {response.status_code}")
        
        if response.status_code == 200:
            print("✓ Client reports view works correctly")
            return True
        else:
            print(f"❌ Unexpected status code: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Error testing view: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_client_report_service():
    """Test that the ClientReportService works correctly"""
    print("\nTesting ClientReportService...")
    
    try:
        # Test get_client_metrics
        metrics = ClientReportService.get_client_metrics()
        print(f"✓ Client metrics: {metrics}")
        
        # Test get_performance_distribution
        distribution = ClientReportService.get_performance_distribution()
        print(f"✓ Performance distribution: {distribution}")
        
        # Test get_top_performers
        top_performers = ClientReportService.get_top_performers(limit=5)
        print(f"✓ Top performers count: {len(top_performers)}")
        
        print("✓ ClientReportService works correctly")
        return True
        
    except Exception as e:
        print(f"❌ Error testing service: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    print("=" * 60)
    print("Client Reports View Test")
    print("=" * 60)
    
    service_ok = test_client_report_service()
    view_ok = test_client_reports_view()
    
    print("\n" + "=" * 60)
    if service_ok and view_ok:
        print("✅ All tests passed!")
    else:
        print("❌ Some tests failed")
    print("=" * 60)
