#!/usr/bin/env python
"""
Test that loans can be rolled over unlimited times after the fix.
"""
import os
import django
from decimal import Decimal

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

from django.utils import timezone
from loans.models import Loan, RolloverRequest, LoanApplication
from users.models import CustomUser as User
from datetime import timedelta

def test_unlimited_rollovers():
    """Test that a loan can be rolled over multiple times"""
    print("\n" + "="*80)
    print("TESTING: UNLIMITED LOAN ROLLOVERS")
    print("="*80)
    
    # Find or create a test borrower
    print("\n1. Setting up test data...")
    test_user = User.objects.filter(
        first_name__icontains='test',
        role='borrower'
    ).first()
    
    if not test_user:
        print("  ✗ No test borrower found. Please create a test user first.")
        return False
    
    print(f"  ✓ Using borrower: {test_user.get_full_name()}")
    
    # Find an active loan for this borrower
    test_loan = Loan.objects.filter(
        borrower=test_user,
        status='active'
    ).first()
    
    if not test_loan:
        print("  ✗ No active loans found for test user")
        return False
    
    print(f"  ✓ Found loan: {test_loan.loan_number}")
    print(f"    Status: {test_loan.status}")
    print(f"    Is Rolled Over: {test_loan.is_rolled_over}")
    print(f"    Principal: KES {test_loan.principal_amount:,.2f}")
    print(f"    Outstanding: KES {test_loan.outstanding_amount:,.2f}")
    
    # Get current rollover count
    initial_rollover_count = RolloverRequest.objects.filter(
        loan=test_loan,
        status='approved'
    ).count()
    
    print(f"    Current rollover count: {initial_rollover_count}")
    
    # Test multiple rollovers
    print("\n2. Testing multiple rollovers...")
    
    admin_user = User.objects.filter(role='admin').first()
    if not admin_user:
        print("  ✗ No admin user found")
        return False
    
    target_rollovers = 3  # We'll do 3 rollovers to test
    success_count = 0
    
    for i in range(1, target_rollovers + 1):
        print(f"\n  Rollover #{i}:")
        
        # Check if loan is active
        test_loan.refresh_from_db()
        if test_loan.status != 'active':
            print(f"    ✗ Loan status is '{test_loan.status}', not 'active'")
            break
        
        print(f"    ✓ Loan status: {test_loan.status}")
        print(f"    ✓ Is rolled over: {test_loan.is_rolled_over}")
        
        # Create rollover request
        new_duration = 90  # 3 months
        new_amount = test_loan.outstanding_amount
        
        try:
            rollover_request = RolloverRequest.objects.create(
                loan=test_loan,
                borrower=test_user,
                requested_amount=new_amount,
                requested_duration=new_duration,
                reason=f"Test rollover #{i}",
                status='pending'
            )
            print(f"    ✓ Created rollover request")
            
            # Approve the rollover
            updated_loan = rollover_request.approve(
                approved_by=admin_user,
                notes=f"Test approval #{i}"
            )
            
            print(f"    ✓ Rollover approved!")
            print(f"      New duration: {updated_loan.duration_days} days")
            print(f"      New principal: KES {updated_loan.principal_amount:,.2f}")
            print(f"      Is rolled over: {updated_loan.is_rolled_over}")
            print(f"      Status: {updated_loan.status}")
            
            success_count += 1
            test_loan = updated_loan  # Update reference for next iteration
            
        except Exception as e:
            print(f"    ✗ Error during rollover #{i}: {e}")
            import traceback
            traceback.print_exc()
            break
    
    # Final verification
    print("\n3. Final verification...")
    test_loan.refresh_from_db()
    
    final_rollover_count = RolloverRequest.objects.filter(
        loan=test_loan,
        status='approved'
    ).count()
    
    print(f"  Initial rollover count: {initial_rollover_count}")
    print(f"  Final rollover count: {final_rollover_count}")
    print(f"  New rollovers created: {final_rollover_count - initial_rollover_count}")
    print(f"  Successful rollovers: {success_count}/{target_rollovers}")
    
    # Check loan state
    print(f"\n  Final loan state:")
    print(f"    Status: {test_loan.status}")
    print(f"    Is rolled over: {test_loan.is_rolled_over}")
    print(f"    Principal: KES {test_loan.principal_amount:,.2f}")
    print(f"    Duration: {test_loan.duration_days} days")
    
    # Success criteria
    success = success_count == target_rollovers
    
    print("\n" + "="*80)
    if success:
        print("✓✓✓ TEST PASSED - Loan can be rolled over unlimited times!")
        print("="*80)
        print(f"\n🎉 Successfully rolled over the same loan {success_count} times")
        print("   The fix is working correctly!")
    else:
        print("✗✗✗ TEST FAILED - Could not complete all rollovers")
        print("="*80)
        print(f"\n⚠️  Only {success_count} out of {target_rollovers} rollovers succeeded")
    
    print("\n")
    return success

if __name__ == '__main__':
    test_unlimited_rollovers()
