#!/usr/bin/env python
"""
Test script for enhanced reports functionality
"""
import os
import sys
import django

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

from django.test import RequestFactory
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
from reports.views import (
    enhanced_loans_in_arrears_report,
    enhanced_processing_fees_report,
    enhanced_interest_income_report,
    enhanced_loans_due_report,
    enhanced_delinquent_loans_report,
    enhanced_registration_fees_report
)
from users.models import CustomUser

def create_test_request(path='/', user=None):
    """Create a test request with session"""
    factory = RequestFactory()
    request = factory.get(path)
    
    # Add session manually
    from django.contrib.sessions.backends.db import SessionStore
    request.session = SessionStore()
    request.session.create()
    
    # Add user
    if user:
        request.user = user
    else:
        request.user = AnonymousUser()
    
    return request

def test_enhanced_reports():
    """Test all enhanced report views"""
    print("Testing Enhanced Reports...")
    
    # Create a test user
    try:
        user = CustomUser.objects.filter(is_staff=True).first()
        if not user:
            print("No staff user found. Creating test user...")
            user = CustomUser.objects.create_user(
                username='testadmin',
                email='test@example.com',
                password='testpass123',
                first_name='Test',
                last_name='Admin',
                is_staff=True,
                is_superuser=True
            )
    except Exception as e:
        print(f"Error creating test user: {e}")
        return False
    
    # Test each enhanced report
    reports_to_test = [
        ('Loans in Arrears', enhanced_loans_in_arrears_report),
        ('Processing Fees', enhanced_processing_fees_report),
        ('Interest Income', enhanced_interest_income_report),
        ('Loans Due', enhanced_loans_due_report),
        ('Delinquent Loans', enhanced_delinquent_loans_report),
        ('Registration Fees', enhanced_registration_fees_report),
    ]
    
    success_count = 0
    total_count = len(reports_to_test)
    
    for report_name, report_view in reports_to_test:
        try:
            print(f"\nTesting {report_name} Report...")
            request = create_test_request(user=user)
            response = report_view(request)
            
            if response.status_code == 200:
                print(f"✓ {report_name} Report: SUCCESS (Status: {response.status_code})")
                success_count += 1
            else:
                print(f"✗ {report_name} Report: FAILED (Status: {response.status_code})")
                
        except Exception as e:
            print(f"✗ {report_name} Report: ERROR - {str(e)}")
    
    print(f"\n{'='*50}")
    print(f"Test Results: {success_count}/{total_count} reports working")
    print(f"Success Rate: {(success_count/total_count)*100:.1f}%")
    
    if success_count == total_count:
        print("🎉 All enhanced reports are working correctly!")
        return True
    else:
        print("⚠️  Some reports need attention.")
        return False

def test_template_rendering():
    """Test that templates can be rendered"""
    print("\nTesting Template Rendering...")
    
    from django.template.loader import get_template
    from django.template import Context
    
    templates_to_test = [
        'reports/enhanced_loans_in_arrears_report.html',
        'reports/enhanced_processing_fees_report.html',
        'reports/enhanced_interest_income_report.html',
        'reports/enhanced_loans_due_report.html',
        'reports/enhanced_delinquent_loans_report.html',
        'reports/enhanced_registration_fees_report.html',
    ]
    
    success_count = 0
    total_count = len(templates_to_test)
    
    for template_name in templates_to_test:
        try:
            template = get_template(template_name)
            print(f"✓ Template {template_name}: Found")
            success_count += 1
        except Exception as e:
            print(f"✗ Template {template_name}: ERROR - {str(e)}")
    
    print(f"\nTemplate Results: {success_count}/{total_count} templates found")
    return success_count == total_count

if __name__ == '__main__':
    print("Enhanced Reports Test Suite")
    print("="*50)
    
    # Test template availability
    templates_ok = test_template_rendering()
    
    # Test report functionality
    reports_ok = test_enhanced_reports()
    
    print(f"\n{'='*50}")
    print("FINAL RESULTS:")
    print(f"Templates: {'✓ PASS' if templates_ok else '✗ FAIL'}")
    print(f"Reports: {'✓ PASS' if reports_ok else '✗ FAIL'}")
    
    if templates_ok and reports_ok:
        print("\n🎉 All enhanced reports are ready for use!")
        print("\nYou can now access the enhanced reports at:")
        print("- /reports/loans-in-arrears/")
        print("- /reports/processing-fees/")
        print("- /reports/interest-income/")
        print("- /reports/loans-due/")
        print("- /reports/delinquent-loans/")
        print("- /reports/registration-fees/")
    else:
        print("\n⚠️  Some issues need to be resolved before the reports are fully functional.")
    
    sys.exit(0 if (templates_ok and reports_ok) else 1)