#!/usr/bin/env python
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import RequestFactory
from django.contrib.auth import get_user_model
from django.contrib.sessions.middleware import SessionMiddleware
from reports.views import reports_dashboard
from reports.simple_reports_service import simple_reports_service

def test_dashboard_context():
    print("=== Testing Dashboard Context ===")
    
    # Test the service directly first
    print("\n1. Testing service directly:")
    try:
        dashboard_data = simple_reports_service.generate_dashboard_data()
        print(f"Service returned data successfully!")
        print(f"Active loans: {dashboard_data['summary_metrics']['total_active_loans']}")
        print(f"Portfolio value: {dashboard_data['summary_metrics']['total_portfolio_value']}")
        print(f"Processing fees: {dashboard_data['processing_fees_current_month']['summary']['total_processing_fees']}")
    except Exception as e:
        print(f"Service failed: {e}")
        import traceback
        traceback.print_exc()
        return
    
    # Test the view
    print("\n2. Testing view:")
    factory = RequestFactory()
    request = factory.get('/reports/')
    
    # Add session middleware
    middleware = SessionMiddleware(lambda x: None)
    middleware.process_request(request)
    request.session.save()
    
    # Create a mock user
    User = get_user_model()
    user = User.objects.first()
    if not user:
        print("No users found in database")
        return
    
    request.user = user
    
    try:
        # Call the dashboard view
        response = reports_dashboard(request)
        print(f"View returned status: {response.status_code}")
        
        # Check if the response contains the expected data
        content = response.content.decode('utf-8')
        
        # Look for specific values in the rendered HTML
        if 'KES 546,859' in content or '546859' in content:
            print("✓ Portfolio value found in rendered HTML")
        else:
            print("✗ Portfolio value NOT found in rendered HTML")
            
        if 'KES 3,150' in content or '3150' in content:
            print("✓ Processing fees found in rendered HTML")
        else:
            print("✗ Processing fees NOT found in rendered HTML")
            
        if '21' in content and 'Active Loans' in content:
            print("✓ Active loans count found in rendered HTML")
        else:
            print("✗ Active loans count NOT found in rendered HTML")
            
        # Check for zero values that shouldn't be there
        if 'KES 0' in content:
            print("⚠ Found KES 0 values in rendered HTML - this might indicate an issue")
        
    except Exception as e:
        print(f"Error calling dashboard view: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    test_dashboard_context()