#!/usr/bin/env python
"""
Test PDF Generation for Loans Dashboard
Run this to verify PDF generation works before deploying
"""

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"""
    print("Testing PDF Generation...")
    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']}")
            print(f"   Content-Disposition: {response.get('Content-Disposition', 'N/A')}")
            
            # Check if it's actually a PDF
            if response['Content-Type'] == 'application/pdf':
                print("✅ Response is a valid PDF")
                
                # 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.")
                return True
            else:
                print(f"⚠���  Response is not a PDF: {response['Content-Type']}")
                print(f"   Content preview: {response.content[:200]}")
                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

def test_reportlab_installation():
    """Test that reportlab is installed"""
    print("\n🔍 Checking ReportLab installation...")
    print("-" * 50)
    
    try:
        import reportlab
        print(f"✅ ReportLab is installed (version {reportlab.Version})")
        
        # Test basic imports
        from reportlab.lib.pagesizes import A4
        from reportlab.platypus import SimpleDocTemplate
        from reportlab.lib import colors
        print("✅ All required ReportLab modules are available")
        return True
        
    except ImportError as e:
        print(f"❌ ReportLab is not installed: {str(e)}")
        print("\n💡 Install with: pip install reportlab")
        return False

def check_database_data():
    """Check if there's data to generate reports from"""
    print("\n📊 Checking database data...")
    print("-" * 50)
    
    try:
        from loans.models import Loan
        from users.models import CustomUser
        
        loan_count = Loan.objects.count()
        borrower_count = CustomUser.objects.filter(role='borrower').count()
        
        print(f"   Loans in database: {loan_count}")
        print(f"   Borrowers in database: {borrower_count}")
        
        if loan_count > 0:
            print("✅ Database has loan data")
            return True
        else:
            print("⚠️  No loans in database (PDF will be empty but should still generate)")
            return True
            
    except Exception as e:
        print(f"❌ Error checking database: {str(e)}")
        return False

if __name__ == '__main__':
    print("\n" + "=" * 50)
    print("PDF GENERATION TEST SUITE")
    print("=" * 50)
    
    # Run tests
    reportlab_ok = test_reportlab_installation()
    data_ok = check_database_data()
    pdf_ok = test_pdf_generation()
    
    # Summary
    print("\n" + "=" * 50)
    print("TEST SUMMARY")
    print("=" * 50)
    print(f"ReportLab Installation: {'✅ PASS' if reportlab_ok else '❌ FAIL'}")
    print(f"Database Data Check:    {'✅ PASS' if data_ok else '❌ FAIL'}")
    print(f"PDF Generation:         {'✅ PASS' if pdf_ok else '❌ FAIL'}")
    
    if reportlab_ok and pdf_ok:
        print("\n🎉 All tests passed! Ready to deploy.")
        sys.exit(0)
    else:
        print("\n⚠️  Some tests failed. Please fix issues before deploying.")
        sys.exit(1)
