#!/usr/bin/env python3
"""
Test script to verify rollover system fixes
"""

import os
import sys
import django
from decimal import Decimal, DecimalException

# 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

def test_decimal_conversion():
    """Test decimal conversion fixes"""
    print("🧪 Testing Decimal Conversion Fixes")
    print("-" * 40)
    
    test_cases = [
        "15000.00",
        "15,000.00", 
        "15000",
        "15,000",
        "",
        "invalid",
        "0",
        "-100"
    ]
    
    for test_value in test_cases:
        try:
            # Simulate the fixed conversion logic
            if test_value:
                amount = Decimal(str(test_value).replace(',', ''))
                if amount <= 0:
                    print(f"  ❌ {test_value} -> Invalid (amount <= 0)")
                else:
                    print(f"  ✅ {test_value} -> {amount}")
            else:
                print(f"  ❌ {test_value} -> Invalid (empty)")
        except (ValueError, TypeError, DecimalException) as e:
            print(f"  ❌ {test_value} -> Error: {e}")
    
    print()

def test_loan_status_separation():
    """Test that active and rolled over loans are properly separated"""
    print("🧪 Testing Loan Status Separation")
    print("-" * 40)
    
    # Count loans by status
    active_loans = Loan.objects.filter(status='active').count()
    rolled_over_loans = Loan.objects.filter(status='rolled_over').count()
    
    print(f"  📊 Active loans: {active_loans}")
    print(f"  🔄 Rolled over loans: {rolled_over_loans}")
    
    # Check for any loans that might be both active and rolled over (should be 0)
    conflicted_loans = Loan.objects.filter(status='active', is_rolled_over=True).count()
    if conflicted_loans == 0:
        print(f"  ✅ No conflicted loans (active + rolled over)")
    else:
        print(f"  ❌ Found {conflicted_loans} loans that are both active and rolled over")
    
    print()

def test_rollover_request_fields():
    """Test rollover request enhanced fields"""
    print("🧪 Testing Rollover Request Enhanced Fields")
    print("-" * 40)
    
    rollover_requests = RolloverRequest.objects.all()[:3]
    
    if rollover_requests.exists():
        for request in rollover_requests:
            print(f"  📝 Request {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()
    else:
        print("  ℹ️ No rollover requests found")
    
    print()

def test_status_validation():
    """Test loan status validation"""
    print("🧪 Testing Loan Status Validation")
    print("-" * 40)
    
    # Test with existing loans
    test_loan = Loan.objects.filter(status='active').first()
    
    if test_loan:
        print(f"  📋 Testing with loan: {test_loan.loan_number}")
        
        # Test valid transitions
        valid_transitions = ['paid', 'defaulted', 'rolled_over', 'written_off']
        for new_status in valid_transitions:
            try:
                test_loan.validate_status_transition(new_status)
                print(f"  ✅ active -> {new_status}: Valid")
            except ValueError as e:
                print(f"  ❌ active -> {new_status}: {e}")
        
        # Test invalid transition (rolled_over back to active)
        if test_loan.status == 'rolled_over':
            try:
                test_loan.validate_status_transition('active')
                print(f"  ❌ rolled_over -> active: Should be invalid but passed")
            except ValueError as e:
                print(f"  ✅ rolled_over -> active: Correctly blocked - {e}")
    else:
        print("  ℹ️ No active loans found for testing")
    
    print()

def main():
    """Run all tests"""
    print("🚀 Testing Enhanced Rollover System Fixes")
    print("=" * 50)
    
    test_decimal_conversion()
    test_loan_status_separation()
    test_rollover_request_fields()
    test_status_validation()
    
    print("🎯 Test Summary:")
    print("  • Decimal conversion fixes tested")
    print("  • Loan status separation verified")
    print("  • Enhanced rollover fields confirmed")
    print("  • Status validation rules checked")
    print()
    print("✨ All tests completed!")

if __name__ == "__main__":
    main()