"""
Test script to verify that rolled-over loans are properly excluded from all reports
"""
import os
import django

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

from django.utils import timezone
from loans.models import Loan
from reports.simple_reports_service import SimpleReportsService
from reports.comprehensive_reports import ComprehensiveReportsService
from decimal import Decimal
from datetime import timedelta

def test_rollover_exclusion():
    """Test that rolled-over loans are excluded from all reports"""
    
    print("=" * 80)
    print("TESTING ROLLOVER LOAN EXCLUSION FROM REPORTS")
    print("=" * 80)
    
    # Get all active loans
    active_loans = Loan.objects.filter(status='active', is_deleted=False)
    print(f"\n1. Total active loans (including rolled-over): {active_loans.count()}")
    
    # Get rolled-over loans
    rolled_over_loans = Loan.objects.filter(
        is_rolled_over=True
    ) | Loan.objects.filter(status='rolled_over')
    print(f"2. Total rolled-over loans: {rolled_over_loans.count()}")
    
    if rolled_over_loans.exists():
        print("\n   Rolled-over loans found:")
        for loan in rolled_over_loans[:5]:  # Show first 5
            print(f"   - {loan.loan_number}: status={loan.status}, is_rolled_over={loan.is_rolled_over}")
    
    # Get active loans excluding rolled-over
    active_non_rolled = Loan.objects.filter(
        status='active',
        is_deleted=False,
        is_rolled_over=False
    ).exclude(status='rolled_over')
    print(f"\n3. Active loans (excluding rolled-over): {active_non_rolled.count()}")
    
    # Test SimpleReportsService
    print("\n" + "=" * 80)
    print("TESTING SIMPLE REPORTS SERVICE")
    print("=" * 80)
    
    service = SimpleReportsService()
    
    # Test summary metrics
    print("\n4. Testing get_summary_metrics()...")
    summary = service.get_summary_metrics()
    print(f"   - Total active loans in summary: {summary['total_active_loans']}")
    print(f"   - Expected (excluding rolled-over): {active_non_rolled.count()}")
    
    if summary['total_active_loans'] == active_non_rolled.count():
        print("   ✅ PASS: Summary metrics correctly excludes rolled-over loans")
    else:
        print("   ❌ FAIL: Summary metrics includes rolled-over loans")
    
    # Test loans due today
    print("\n5. Testing get_loans_due_today()...")
    loans_due = service.get_loans_due_today()
    loans_due_count = len(loans_due['loans'])
    print(f"   - Loans due today: {loans_due_count}")
    
    # Check if any rolled-over loans are in the results
    rolled_over_in_due = 0
    for loan_data in loans_due['loans']:
        loan = Loan.objects.get(id=loan_data['id'])
        if loan.is_rolled_over or loan.status == 'rolled_over':
            rolled_over_in_due += 1
            print(f"   ❌ Found rolled-over loan in due today: {loan.loan_number}")
    
    if rolled_over_in_due == 0:
        print("   ✅ PASS: Loans due today correctly excludes rolled-over loans")
    else:
        print(f"   ❌ FAIL: Found {rolled_over_in_due} rolled-over loans in due today")
    
    # Test delinquent loans
    print("\n6. Testing get_delinquent_loans()...")
    delinquent = service.get_delinquent_loans()
    total_delinquent = delinquent['summary']['total_delinquent']
    print(f"   - Total delinquent loans: {total_delinquent}")
    
    # Test overdue loans analytics
    print("\n7. Testing get_overdue_loans_analytics()...")
    overdue = service.get_overdue_loans_analytics()
    total_overdue = overdue['summary']['total_overdue_loans']
    print(f"   - Total overdue loans: {total_overdue}")
    
    # Test ComprehensiveReportsService
    print("\n" + "=" * 80)
    print("TESTING COMPREHENSIVE REPORTS SERVICE")
    print("=" * 80)
    
    comp_service = ComprehensiveReportsService()
    
    # Test loans due report
    print("\n8. Testing get_loans_due_report()...")
    today = timezone.now().date()
    loans_due_report = comp_service.get_loans_due_report(
        start_date=today,
        end_date=today + timedelta(days=30)
    )
    loans_due_comp_count = len(loans_due_report['loans'])
    print(f"   - Loans due (next 30 days): {loans_due_comp_count}")
    
    # Check if any rolled-over loans are in the results
    rolled_over_in_comp_due = 0
    for loan_data in loans_due_report['loans']:
        loan = Loan.objects.get(id=loan_data['id'])
        if loan.is_rolled_over or loan.status == 'rolled_over':
            rolled_over_in_comp_due += 1
            print(f"   ❌ Found rolled-over loan: {loan.loan_number}")
    
    if rolled_over_in_comp_due == 0:
        print("   ✅ PASS: Comprehensive loans due report correctly excludes rolled-over loans")
    else:
        print(f"   ❌ FAIL: Found {rolled_over_in_comp_due} rolled-over loans")
    
    # Test delinquent loans report
    print("\n9. Testing get_delinquent_loans_report()...")
    delinquent_report = comp_service.get_delinquent_loans_report()
    delinquent_comp_count = len(delinquent_report['loans'])
    print(f"   - Delinquent loans: {delinquent_comp_count}")
    
    # Check if any rolled-over loans are in the results
    rolled_over_in_comp_delinquent = 0
    for loan_data in delinquent_report['loans']:
        loan = Loan.objects.get(id=loan_data['id'])
        if loan.is_rolled_over or loan.status == 'rolled_over':
            rolled_over_in_comp_delinquent += 1
            print(f"   ❌ Found rolled-over loan: {loan.loan_number}")
    
    if rolled_over_in_comp_delinquent == 0:
        print("   ✅ PASS: Comprehensive delinquent report correctly excludes rolled-over loans")
    else:
        print(f"   ❌ FAIL: Found {rolled_over_in_comp_delinquent} rolled-over loans")
    
    # Test loans in arrears report
    print("\n10. Testing get_loans_in_arrears_report()...")
    arrears_report = comp_service.get_loans_in_arrears_report()
    arrears_comp_count = len(arrears_report['loans'])
    print(f"   - Loans in arrears: {arrears_comp_count}")
    
    # Check if any rolled-over loans are in the results
    rolled_over_in_comp_arrears = 0
    for loan_data in arrears_report['loans']:
        loan = Loan.objects.get(id=loan_data['id'])
        if loan.is_rolled_over or loan.status == 'rolled_over':
            rolled_over_in_comp_arrears += 1
            print(f"   ❌ Found rolled-over loan: {loan.loan_number}")
    
    if rolled_over_in_comp_arrears == 0:
        print("   ✅ PASS: Comprehensive arrears report correctly excludes rolled-over loans")
    else:
        print(f"   ❌ FAIL: Found {rolled_over_in_comp_arrears} rolled-over loans")
    
    # Final summary
    print("\n" + "=" * 80)
    print("TEST SUMMARY")
    print("=" * 80)
    
    total_tests = 6
    passed_tests = 0
    
    if summary['total_active_loans'] == active_non_rolled.count():
        passed_tests += 1
    if rolled_over_in_due == 0:
        passed_tests += 1
    if rolled_over_in_comp_due == 0:
        passed_tests += 1
    if rolled_over_in_comp_delinquent == 0:
        passed_tests += 1
    if rolled_over_in_comp_arrears == 0:
        passed_tests += 1
    
    print(f"\nTests passed: {passed_tests}/{total_tests}")
    
    if passed_tests == total_tests:
        print("\n✅ ALL TESTS PASSED! Rolled-over loans are properly excluded from all reports.")
    else:
        print(f"\n❌ {total_tests - passed_tests} TEST(S) FAILED! Some reports still include rolled-over loans.")
    
    print("\n" + "=" * 80)

if __name__ == '__main__':
    test_rollover_exclusion()
