"""
Verify registration fees are displaying correctly
"""
import os
import django

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

from django.test import Client, RequestFactory
from users.models import CustomUser, Branch
from reports.views import enhanced_registration_fees_report

def verify_display():
    """Verify the registration fees display"""
    print("=" * 80)
    print("VERIFYING REGISTRATION FEES DISPLAY")
    print("=" * 80)
    
    # Check branches
    branches = Branch.objects.all()
    print(f"\n✓ Total branches: {branches.count()}")
    
    if branches.exists():
        main_branch = branches.first()
        print(f"✓ Main branch: {main_branch.name}")
    else:
        print("✗ No branches found")
        return
    
    # Check borrowers
    borrowers = CustomUser.objects.filter(role='borrower')
    print(f"\n✓ Total borrowers: {borrowers.count()}")
    
    # Check borrowers with fees
    borrowers_with_fees = borrowers.filter(registration_fee_amount__gt=0)
    print(f"✓ Borrowers with fees: {borrowers_with_fees.count()}")
    
    # Check borrowers by branch
    for branch in branches:
        branch_borrowers = borrowers.filter(branch=branch, registration_fee_amount__gt=0)
        print(f"  - {branch.name}: {branch_borrowers.count()} borrowers with fees")
    
    # Test the view directly
    print("\n" + "=" * 80)
    print("TESTING VIEW DIRECTLY")
    print("=" * 80)
    
    # Create a request
    factory = RequestFactory()
    request = factory.get('/reports/registration-fees/')
    
    # Get or create a staff user
    staff_user = CustomUser.objects.filter(role='staff').first()
    if not staff_user:
        staff_user = CustomUser.objects.create_user(
            username='teststaff2',
            email='teststaff2@example.com',
            password='testpass123',
            role='staff',
            first_name='Test',
            last_name='Staff'
        )
    
    request.user = staff_user
    request.session = {}
    
    # Test without branch filtering
    print("\n1. Testing without branch filter:")
    try:
        response = enhanced_registration_fees_report(request)
        print(f"   ✓ Response status: {response.status_code}")
        
        if response.status_code == 200:
            content = response.content.decode('utf-8')
            
            # Check for data indicators
            if 'KSh 4,500' in content or 'KSh 4500' in content or '4,500' in content:
                print("   ✓ Found income data in response!")
            else:
                print("   ⚠ Income data not found in response")
            
            if '12' in content:
                print("   ✓ Found registration count in response!")
            else:
                print("   ⚠ Registration count not found")
                
    except Exception as e:
        print(f"   ✗ Error: {e}")
        import traceback
        traceback.print_exc()
    
    # Test with branch filtering
    if branches.exists():
        print(f"\n2. Testing with branch filter (Branch: {main_branch.name}):")
        request.session['selected_branch_id'] = str(main_branch.id)
        
        try:
            response = enhanced_registration_fees_report(request)
            print(f"   ✓ Response status: {response.status_code}")
            
            if response.status_code == 200:
                content = response.content.decode('utf-8')
                
                if 'KSh' in content and any(char.isdigit() for char in content):
                    print("   ✓ Found financial data in response!")
                else:
                    print("   ⚠ Financial data not found in response")
                    
        except Exception as e:
            print(f"   ✗ Error: {e}")
    
    print("\n" + "=" * 80)
    print("VERIFICATION COMPLETED")
    print("=" * 80)

if __name__ == '__main__':
    verify_display()
