#!/usr/bin/env python
"""
Quick test to verify the PDF generation fix works
"""

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 loans.minimal_analytics import generate_loans_dashboard_pdf

def test_pdf_generation():
    """Test that PDF generation works without field errors"""
    print("Testing PDF Generation Fix...")
    print("-" * 50)
    
    try:
        # Create a mock request
        factory = RequestFactory()
        request = factory.get('/loans/reports/pdf/loans-dashboard/')
        
        # Get a user for authentication
        User = get_user_model()
        user = User.objects.filter(is_staff=True).first()
        
        if not user:
            print("⚠️  No staff user found. Creating test user...")
            user = User.objects.create_user(
                username='test_pdf_user',
                email='test@example.com',
                password='testpass123',
                is_staff=True
            )
            print("✅ Test user created")
        
        request.user = user
        request.session = {}
        
        # Test PDF generation
        print("\n📄 Generating PDF...")
        response = generate_loans_dashboard_pdf(request)
        
        # Check response
        if response.status_code == 200:
            print("✅ PDF generated successfully!")
            print(f"   Content-Type: {response['Content-Type']}")
            
            # Check if it's actually a PDF
            if response['Content-Type'] == 'application/pdf':
                print("✅ Response is a valid PDF (not text file)")
                
                # Save to file for inspection
                with open('test_loans_dashboard.pdf', 'wb') as f:
                    f.write(response.content)
                print("✅ PDF saved as 'test_loans_dashboard.pdf'")
                print("\n🎉 SUCCESS! PDF generation is working correctly.")
                print("   No 'amount_paid' field errors!")
                return True
            elif response['Content-Type'] == 'text/plain':
                print("⚠️  Response is text/plain - checking for errors...")
                content = response.content.decode('utf-8')
                print(f"   Content: {content[:200]}")
                
                if 'Error generating PDF' in content:
                    print("❌ PDF generation failed with error")
                    print(f"   Full error: {content}")
                    return False
                else:
                    print("⚠️  Unexpected text response")
                    return False
            else:
                print(f"⚠️  Unexpected content type: {response['Content-Type']}")
                return False
        else:
            print(f"❌ Failed with status code: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Error during PDF generation: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    print("\n" + "=" * 50)
    print("PDF GENERATION FIX TEST")
    print("=" * 50)
    
    success = test_pdf_generation()
    
    print("\n" + "=" * 50)
    if success:
        print("✅ TEST PASSED - Ready to deploy!")
        sys.exit(0)
    else:
        print("❌ TEST FAILED - Please fix issues before deploying")
        sys.exit(1)
