#!/usr/bin/env python
"""
Test script to verify all page fixes are working
"""
import os
import sys
import django

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

from django.contrib.auth import get_user_model
from utils.models import Document, Notification
from loans.models import Repayment

User = get_user_model()

def test_documents_page():
    """Test Documents page data"""
    print("🔍 TESTING DOCUMENTS PAGE...")
    print("=" * 40)
    
    total_docs = Document.objects.count()
    print(f"✅ Total documents: {total_docs}")
    
    if total_docs > 0:
        # Test documents by type
        doc_types = Document.objects.values_list('document_type', flat=True).distinct()
        print(f"✅ Document types: {list(doc_types)}")
        
        # Test branch filtering
        from users.models import Branch
        for branch in Branch.objects.all():
            branch_docs = Document.objects.filter(uploaded_by__branch=branch).count()
            if branch_docs > 0:
                print(f"✅ {branch.name}: {branch_docs} documents")
    else:
        print("❌ No documents found!")
        return False
    
    return True

def test_system_alerts():
    """Test System Alerts"""
    print("\n🔔 TESTING SYSTEM ALERTS...")
    print("=" * 40)
    
    # Test system alerts (notifications without user)
    system_alerts = Notification.objects.filter(user__isnull=True)
    print(f"✅ System alerts: {system_alerts.count()}")
    
    # Test notification types
    notification_types = Notification.objects.values_list('notification_type', flat=True).distinct()
    proper_types = [t for t in notification_types if t != 'system_maintenance']
    print(f"✅ Proper notification types: {len(proper_types)}")
    
    # Test priority distribution
    for priority in ['urgent', 'high', 'medium', 'low']:
        count = system_alerts.filter(priority=priority).count()
        if count > 0:
            print(f"✅ {priority.title()} priority: {count}")
    
    return system_alerts.count() > 0

def test_payment_receipts():
    """Test Payment Receipts"""
    print("\n🧾 TESTING PAYMENT RECEIPTS...")
    print("=" * 40)
    
    total_receipts = Repayment.objects.count()
    print(f"✅ Total receipts: {total_receipts}")
    
    if total_receipts > 0:
        # Test recent receipts
        recent_receipts = Repayment.objects.order_by('-payment_date')[:3]
        for receipt in recent_receipts:
            borrower_name = receipt.loan.borrower.get_full_name() if receipt.loan and receipt.loan.borrower else "Unknown"
            receipt_number = getattr(receipt, 'receipt_number', 'N/A')
            print(f"✅ Receipt: {receipt_number} - {borrower_name}")
    else:
        print("❌ No receipts found!")
        return False
    
    return True

def test_reports_statements():
    """Test Reports & Statements"""
    print("\n📊 TESTING REPORTS & STATEMENTS...")
    print("=" * 40)
    
    try:
        from utils.reports import OptimizedReportGenerator
        generator = OptimizedReportGenerator()
        print("✅ Reports module accessible")
        
        # Test data availability
        from loans.models import Loan
        loans_count = Loan.objects.count()
        users_count = User.objects.count()
        
        print(f"✅ Data available - Users: {users_count}, Loans: {loans_count}")
        
        return True
    except Exception as e:
        print(f"❌ Reports module error: {e}")
        return False

def main():
    """Main test function"""
    print("🧪 TESTING ALL PAGE FIXES")
    print("=" * 50)
    
    results = {
        'documents': test_documents_page(),
        'system_alerts': test_system_alerts(),
        'payment_receipts': test_payment_receipts(),
        'reports_statements': test_reports_statements(),
    }
    
    print("\n" + "=" * 50)
    print("📋 TEST RESULTS:")
    
    all_passed = True
    for page, passed in results.items():
        status = "✅ PASS" if passed else "❌ FAIL"
        print(f"  {page.replace('_', ' ').title()}: {status}")
        all_passed &= passed
    
    print("\n" + "=" * 50)
    if all_passed:
        print("🎉 ALL TESTS PASSED!")
        print("\n🌐 Your pages should now work correctly:")
        print("   • Documents page should show documents")
        print("   • Notifications page should show System Alerts")
        print("   • Payment Receipts page should work")
        print("   • Reports & Statements page should be functional")
    else:
        print("❌ SOME TESTS FAILED!")
        print("Check the output above for details.")
    
    return all_passed

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)