"""
Test script to verify rollover report shows ALL rollover entries
Tests the fix for issue where report showed only final rollover state
"""
import os
import sys
import django

# Setup Django
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan, RolloverRequest
from decimal import Decimal

def test_rollover_report_data():
    """Test that rollover report logic shows all rollover entries"""
    
    print("=" * 80)
    print("TESTING ROLLOVER REPORT FIX")
    print("=" * 80)
    
    # Find loan with multiple rollovers (19112026-000004 from local tests)
    test_loan_number = '19112026-000004'
    
    try:
        loan = Loan.objects.get(loan_number=test_loan_number)
        print(f"\n✓ Found test loan: {loan.loan_number}")
        print(f"  Borrower: {loan.borrower.get_full_name()}")
        print(f"  Current Principal: KES {loan.principal_amount:,.2f}")
        print(f"  Is Rolled Over: {loan.is_rolled_over}")
    except Loan.DoesNotExist:
        print(f"\n✗ Test loan {test_loan_number} not found")
        print("  Looking for any loan with multiple rollovers...")
        
        # Find any loan with 2+ rollover requests
        loans_with_multiple_rollovers = []
        for loan in Loan.objects.filter(is_rolled_over=True, is_deleted=False):
            rollover_count = RolloverRequest.objects.filter(
                loan=loan,
                status='approved'
            ).count()
            if rollover_count >= 2:
                loans_with_multiple_rollovers.append((loan, rollover_count))
        
        if not loans_with_multiple_rollovers:
            print("\n✗ No loans with multiple rollovers found in database")
            return
        
        # Use the loan with the most rollovers
        loan, rollover_count = max(loans_with_multiple_rollovers, key=lambda x: x[1])
        print(f"\n✓ Found loan with {rollover_count} rollovers: {loan.loan_number}")
        print(f"  Borrower: {loan.borrower.get_full_name()}")
    
    # Get all approved rollover requests for this loan
    rollover_requests = RolloverRequest.objects.filter(
        loan=loan,
        status='approved'
    ).select_related('reviewed_by').order_by('reviewed_at')
    
    rollover_count = rollover_requests.count()
    
    print(f"\n{'=' * 80}")
    print(f"ROLLOVER HISTORY FOR {loan.loan_number}")
    print(f"{'=' * 80}")
    print(f"Total Approved Rollovers: {rollover_count}")
    print()
    
    if rollover_count == 0:
        print("✗ No approved rollover requests found!")
        return
    
    # Simulate what the report will show
    print(f"{'#':<4} {'Renewed On':<20} {'New Principal':<15} {'Interest':<12} {'Total Owed':<15} {'Renewed By':<20}")
    print("-" * 100)
    
    total_new_principal = Decimal('0')
    total_interest = Decimal('0')
    total_total_owed = Decimal('0')
    
    for idx, rr in enumerate(rollover_requests, 1):
        new_principal = rr.requested_amount
        interest = rr.requested_interest_rate or Decimal('0')
        total_owed = new_principal + interest
        renewed_by = rr.reviewed_by.get_full_name() if rr.reviewed_by else 'Unknown'
        
        print(f"{idx:<4} {rr.reviewed_at.strftime('%Y-%m-%d %H:%M:%S'):<20} "
              f"KES {new_principal:>10,.2f}  KES {interest:>8,.2f}  "
              f"KES {total_owed:>10,.2f}  {renewed_by:<20}")
        
        total_new_principal += new_principal
        total_interest += interest
        total_total_owed += total_owed
    
    print("-" * 100)
    print(f"{'TOTALS':<24} KES {total_new_principal:>10,.2f}  KES {total_interest:>8,.2f}  KES {total_total_owed:>10,.2f}")
    
    # Expected vs Actual
    print(f"\n{'=' * 80}")
    print("REPORT EXPECTATIONS")
    print(f"{'=' * 80}")
    print(f"✓ Report should show {rollover_count} rows (one per rollover)")
    print(f"✓ Each row shows the state AT THAT rollover time")
    print(f"✓ Not just the final loan state")
    
    # Check OLD approach would only show 1 row
    old_approach_count = Loan.objects.filter(
        loan_number=loan.loan_number,
        is_rolled_over=True,
        is_deleted=False
    ).count()
    
    print(f"\n{'=' * 80}")
    print("BEFORE vs AFTER FIX")
    print(f"{'=' * 80}")
    print(f"OLD APPROACH (Loan.objects): Would show {old_approach_count} row (final state only) ✗")
    print(f"NEW APPROACH (RolloverRequest.objects): Shows {rollover_count} rows (all rollovers) ✓")
    
    if rollover_count > 1:
        print(f"\n✅ SUCCESS: Report will now show ALL {rollover_count} rollover entries!")
    else:
        print(f"\n⚠️  WARNING: Only 1 rollover found, test inconclusive")
    
    print(f"\n{'=' * 80}")

if __name__ == '__main__':
    test_rollover_report_data()
