#!/usr/bin/env python3
"""
Test script for the enhanced rollover system
"""

import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import Loan, RolloverRequest, LoanApplication, LoanProduct
from users.models import CustomUser
from decimal import Decimal

def test_rollover_system():
    """Test the enhanced rollover system"""
    print("🔄 Testing Enhanced Rollover System")
    print("=" * 50)
    
    # Check if we have any loans to work with
    loans = Loan.objects.filter(status='active')[:5]
    print(f"📊 Found {loans.count()} active loans")
    
    # Check rolled over loans
    rolled_over_loans = Loan.objects.filter(status='rolled_over')
    print(f"🔄 Found {rolled_over_loans.count()} rolled over loans")
    
    # Check rollover requests
    rollover_requests = RolloverRequest.objects.all()
    print(f"📝 Found {rollover_requests.count()} rollover requests")
    
    # Show the new fields in RolloverRequest
    if rollover_requests.exists():
        print("\n📋 Enhanced Rollover Request Fields:")
        for request in rollover_requests[:3]:
            print(f"  • Request ID: {request.id}")
            print(f"    - Loan: {request.loan.loan_number}")
            print(f"    - Requested Amount: KES {request.requested_amount:,.2f}")
            print(f"    - Requested Duration: {request.requested_duration} days")
            print(f"    - Custom Interest Rate: {request.requested_interest_rate}%")
            print(f"    - Custom Processing Fee: KES {request.requested_processing_fee or 0:,.2f}")
            print(f"    - Status: {request.status}")
            print()
    
    # Test creating a new rollover request
    if loans.exists():
        test_loan = loans.first()
        print(f"🧪 Testing rollover request creation for loan: {test_loan.loan_number}")
        
        try:
            # Create a test rollover request
            rollover_request = RolloverRequest.objects.create(
                loan=test_loan,
                borrower=test_loan.borrower,
                requested_amount=Decimal('15000.00'),
                requested_duration=60,
                requested_interest_rate=Decimal('8.5'),
                requested_processing_fee=Decimal('500.00'),
                reason="Test rollover request for enhanced system",
                rollover_fee=Decimal('750.00')
            )
            print(f"✅ Successfully created rollover request: {rollover_request.id}")
            
            # Test approval process
            print("🔄 Testing rollover approval...")
            new_loan = rollover_request.approve(
                approved_by=test_loan.borrower,  # In real scenario, this would be an admin
                notes="Test approval for enhanced rollover system"
            )
            
            print(f"✅ Rollover approved! New loan created: {new_loan.loan_number}")
            print(f"   - Original loan status: {test_loan.status}")
            print(f"   - New loan status: {new_loan.status}")
            print(f"   - New loan amount: KES {new_loan.principal_amount:,.2f}")
            print(f"   - New loan duration: {new_loan.duration_days} days")
            
            # Refresh the original loan to see status change
            test_loan.refresh_from_db()
            print(f"   - Original loan new status: {test_loan.status}")
            
        except Exception as e:
            print(f"❌ Error testing rollover: {e}")
    
    print("\n🎯 Summary:")
    print(f"  • Active loans (excluding rolled over): {Loan.objects.filter(status='active').count()}")
    print(f"  • Rolled over loans: {Loan.objects.filter(status='rolled_over').count()}")
    print(f"  • Total rollover requests: {RolloverRequest.objects.count()}")
    print(f"  • Pending rollover requests: {RolloverRequest.objects.filter(status='pending').count()}")
    print(f"  • Approved rollover requests: {RolloverRequest.objects.filter(status='approved').count()}")
    
    print("\n✨ Enhanced Rollover System Test Complete!")

if __name__ == "__main__":
    test_rollover_system()