#!/usr/bin/env python
"""
Test script to verify soft-deleted loans are properly filtered from reports
"""
import os
import django

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

from loans.models import Loan
from reports.simple_reports_service import simple_reports_service
from django.utils import timezone

def test_soft_delete_filtering():
    """Test that soft-deleted loans don't appear in reports"""
    
    print("=" * 60)
    print("Testing Soft Delete Filtering")
    print("=" * 60)
    
    # Get all loans
    all_loans = Loan.objects.all()
    active_loans = Loan.objects.filter(status='active')
    deleted_loans = Loan.objects.filter(is_deleted=True)
    
    print(f"\n📊 Database Stats:")
    print(f"   Total loans: {all_loans.count()}")
    print(f"   Active loans: {active_loans.count()}")
    print(f"   Soft-deleted loans: {deleted_loans.count()}")
    
    if deleted_loans.exists():
        print(f"\n🗑️  Soft-Deleted Loans:")
        for loan in deleted_loans[:5]:  # Show first 5
            print(f"   - {loan.loan_number}: {loan.borrower.first_name} {loan.borrower.last_name}")
            print(f"     Deleted at: {loan.deleted_at}")
            print(f"     Status: {loan.status}")
    
    # Test reports service
    print(f"\n🔍 Testing Reports Service:")
    
    # Test summary metrics
    summary = simple_reports_service.get_summary_metrics()
    print(f"\n   Summary Metrics:")
    print(f"   - Total active loans: {summary['total_active_loans']}")
    print(f"   - Should match: {active_loans.filter(is_deleted=False).count()}")
    
    # Test loans due today
    loans_due = simple_reports_service.get_loans_due_today()
    print(f"\n   Loans Due Today:")
    print(f"   - Count: {loans_due['summary']['total_loans_due']}")
    
    # Check if any deleted loans appear in results
    deleted_in_results = False
    for loan_data in loans_due['loans']:
        loan = Loan.objects.get(id=loan_data['id'])
        if loan.is_deleted:
            deleted_in_results = True
            print(f"   ❌ ERROR: Deleted loan found: {loan.loan_number}")
    
    if not deleted_in_results:
        print(f"   ✅ No deleted loans in results")
    
    # Test delinquent loans
    delinquent = simple_reports_service.get_delinquent_loans()
    print(f"\n   Delinquent Loans:")
    print(f"   - Mild: {delinquent['summary']['mild_delinquent_count']}")
    print(f"   - Moderate: {delinquent['summary']['moderate_delinquent_count']}")
    print(f"   - Severe: {delinquent['summary']['severe_delinquent_count']}")
    
    # Test processing fees
    processing_fees = simple_reports_service.get_processing_fees_current_month()
    print(f"\n   Processing Fees (Current Month):")
    print(f"   - Total fees: KSh {processing_fees['summary']['total_processing_fees']:,.2f}")
    print(f"   - Loans processed: {processing_fees['summary']['total_loans_processed']}")
    
    print(f"\n{'=' * 60}")
    print("✅ Soft Delete Filtering Test Complete")
    print("=" * 60)
    
    # Verification
    if deleted_loans.exists():
        print(f"\n⚠️  Note: You have {deleted_loans.count()} soft-deleted loans in the database.")
        print("   These should NOT appear in any reports.")
        print("   If you see them in reports, there's a bug in the filtering.")
    else:
        print(f"\n✅ No soft-deleted loans found in database.")

if __name__ == '__main__':
    test_soft_delete_filtering()
