#!/usr/bin/env python
"""
Test the enhanced processing fees report view
"""
import os
import sys
import django

# Setup Django
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
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 django.contrib.messages.middleware import MessageMiddleware
from reports.views import enhanced_processing_fees_report

User = get_user_model()

print("=" * 80)
print("TESTING ENHANCED PROCESSING FEES REPORT VIEW")
print("=" * 80)

# Create a test request
factory = RequestFactory()
request = factory.get('/reports/processing-fees/')

# Add session
middleware = SessionMiddleware(lambda x: None)
middleware.process_request(request)
request.session.save()

# Add messages
msg_middleware = MessageMiddleware(lambda x: None)
msg_middleware.process_request(request)

# Get or create a test user
try:
    user = User.objects.filter(role='admin').first()
    if not user:
        user = User.objects.create_user(
            username='testadmin',
            email='admin@test.com',
            password='testpass123',
            role='admin',
            first_name='Test',
            last_name='Admin'
        )
except Exception as e:
    print(f"Error creating user: {e}")
    user = User.objects.first()

request.user = user

print("\n1. Testing with default parameters (all_time)...")
try:
    response = enhanced_processing_fees_report(request)
    print(f"   Status Code: {response.status_code}")
    if response.status_code == 200:
        print("   ✅ View rendered successfully")
        # Check context
        if hasattr(response, 'context_data'):
            report_data = response.context_data.get('report_data', {})
            summary = report_data.get('summary', {})
            print(f"   Total Fees: KSh {summary.get('total_processing_fees', 0):,.2f}")
            print(f"   Loans Processed: {summary.get('total_loans_processed', 0)}")
    else:
        print(f"   ⚠️  Unexpected status code: {response.status_code}")
except Exception as e:
    print(f"   ❌ Error: {str(e)}")
    import traceback
    traceback.print_exc()

print("\n2. Testing with current_month period...")
request2 = factory.get('/reports/processing-fees/?period=current_month')
middleware.process_request(request2)
request2.session.save()
msg_middleware.process_request(request2)
request2.user = user

try:
    response = enhanced_processing_fees_report(request2)
    print(f"   Status Code: {response.status_code}")
    if response.status_code == 200:
        print("   ✅ View rendered successfully")
except Exception as e:
    print(f"   ❌ Error: {str(e)}")

print("\n" + "=" * 80)
print("TEST COMPLETE")
print("=" * 80)
