"""
Test the Registration Fees Analytics page
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import Client
from users.models import CustomUser

def test_page():
    """Test the registration fees page"""
    print("=" * 80)
    print("TESTING REGISTRATION FEES ANALYTICS PAGE")
    print("=" * 80)
    
    # Create a test client
    client = Client()
    
    # Get a staff user for login
    staff_user = CustomUser.objects.filter(role='staff').first()
    
    if not staff_user:
        print("\n✗ No staff user found. Creating one...")
        staff_user = CustomUser.objects.create_user(
            username='teststaff',
            email='teststaff@example.com',
            password='testpass123',
            role='staff',
            first_name='Test',
            last_name='Staff'
        )
        print(f"✓ Created staff user: {staff_user.username}")
    
    # Login
    login_success = client.login(username=staff_user.username, password='testpass123')
    
    if not login_success:
        # Try with a known password
        staff_user.set_password('testpass123')
        staff_user.save()
        login_success = client.login(username=staff_user.username, password='testpass123')
    
    print(f"\n✓ Login successful: {login_success}")
    
    if not login_success:
        print("✗ Could not login. Testing without authentication...")
    
    # Test the page
    print("\n" + "=" * 80)
    print("TESTING PAGE ACCESS")
    print("=" * 80)
    
    url = '/reports/registration-fees/'
    print(f"\nTesting URL: {url}")
    
    try:
        response = client.get(url)
        print(f"✓ Response status code: {response.status_code}")
        
        if response.status_code == 200:
            print("✓ Page loaded successfully!")
            
            # Check if the page contains expected content
            content = response.content.decode('utf-8')
            
            checks = [
                ('Registration Fees Analytics', 'Page title'),
                ('Total Registration Income', 'Income metric'),
                ('Total Registrations', 'Registrations metric'),
                ('Average Fee', 'Average fee metric'),
                ('Collection Rate', 'Collection rate metric'),
                ('report_data', 'Report data variable'),
            ]
            
            print("\n" + "=" * 80)
            print("CONTENT CHECKS")
            print("=" * 80)
            
            for check_text, description in checks:
                if check_text in content:
                    print(f"✓ Found: {description}")
                else:
                    print(f"✗ Missing: {description}")
            
            # Check for data in the page
            if 'KSh 4,500' in content or 'KSh 4500' in content:
                print("\n✓ Page contains actual registration fee data!")
            else:
                print("\n⚠ Page may not be showing data (check if data exists)")
                
        elif response.status_code == 302:
            print(f"✓ Redirected to: {response.url}")
            print("  (This is normal if authentication is required)")
        else:
            print(f"✗ Unexpected status code: {response.status_code}")
            
    except Exception as e:
        print(f"✗ Error accessing page: {e}")
        import traceback
        traceback.print_exc()
    
    print("\n" + "=" * 80)
    print("TEST COMPLETED")
    print("=" * 80)

if __name__ == '__main__':
    test_page()
