#!/usr/bin/env python
"""
Test that rolled-over loans maintain total_amount = principal + interest
even after recalculate_amounts() is called
"""
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 decimal import Decimal
from loans.models import Loan

def test_rollover_total_calculation():
    """Test that rolled-over loans keep correct total_amount"""
    print("\n" + "="*80)
    print("TEST: Rolled-Over Loan Total Amount Calculation")
    print("="*80)
    
    # Find a rolled-over loan
    rolled_loan = Loan.objects.filter(is_rolled_over=True).first()
    
    if not rolled_loan:
        print("✗ No rolled-over loans found to test")
        return False
    
    print(f"\n📋 Testing Loan: {rolled_loan.loan_number}")
    print(f"   Status: {rolled_loan.status}")
    print(f"   Is Rolled Over: {rolled_loan.is_rolled_over}")
    
    # Record current values
    principal = rolled_loan.principal_amount
    interest = rolled_loan.interest_amount or Decimal('0')
    expected_total = principal + interest
    current_total = rolled_loan.total_amount
    
    print(f"\n💰 Current Amounts:")
    print(f"   Principal: KES {principal:,.2f}")
    print(f"   Interest: KES {interest:,.2f}")
    print(f"   Expected Total: KES {expected_total:,.2f}")
    print(f"   Current Total: KES {current_total:,.2f}")
    
    # Test 1: Check if current total is correct
    print(f"\n✓ Test 1: Current total_amount is correct")
    if current_total == expected_total:
        print(f"   ✓ PASS: Total = {current_total:,.2f} (principal + interest)")
    else:
        print(f"   ✗ FAIL: Total = {current_total:,.2f}, Expected = {expected_total:,.2f}")
        print(f"   ⚠️  Fixing now...")
        rolled_loan.total_amount = expected_total
        rolled_loan.save()
        print(f"   ✓ Fixed and saved")
    
    # Test 2: Call recalculate_amounts() and verify it preserves the total
    print(f"\n✓ Test 2: recalculate_amounts() preserves rollover total")
    rolled_loan.recalculate_amounts()
    new_total = rolled_loan.total_amount
    
    if new_total == expected_total:
        print(f"   ✓ PASS: Total after recalculate = {new_total:,.2f} (preserved!)")
    else:
        print(f"   ✗ FAIL: Total after recalculate = {new_total:,.2f}, Expected = {expected_total:,.2f}")
        return False
    
    # Test 3: Save and reload to verify persistence
    print(f"\n✓ Test 3: Total persists after save and reload")
    rolled_loan.save()
    reloaded_loan = Loan.objects.get(pk=rolled_loan.pk)
    final_total = reloaded_loan.total_amount
    
    if final_total == expected_total:
        print(f"   ✓ PASS: Total after save/reload = {final_total:,.2f} (preserved!)")
    else:
        print(f"   ✗ FAIL: Total after save/reload = {final_total:,.2f}, Expected = {expected_total:,.2f}")
        return False
    
    # Test 4: Check regular (non-rolled) loan behavior
    print(f"\n✓ Test 4: Regular loans still use total = principal")
    regular_loan = Loan.objects.filter(is_rolled_over=False, status='active').first()
    
    if regular_loan:
        print(f"   Testing Loan: {regular_loan.loan_number}")
        regular_loan.recalculate_amounts()
        if regular_loan.total_amount == regular_loan.principal_amount:
            print(f"   ✓ PASS: Regular loan total = principal = {regular_loan.total_amount:,.2f}")
        else:
            print(f"   ✗ FAIL: Regular loan total = {regular_loan.total_amount:,.2f}, Expected = {regular_loan.principal_amount:,.2f}")
            return False
    else:
        print(f"   ⚠️  No regular loans found to test")
    
    print("\n" + "="*80)
    print("✓✓✓ ALL TESTS PASSED! ✓✓✓")
    print("="*80)
    print("\n✅ Rolled-over loans correctly maintain total_amount = principal + interest")
    print("✅ Regular loans correctly maintain total_amount = principal")
    print("✅ recalculate_amounts() respects loan type\n")
    
    return True

if __name__ == '__main__':
    success = test_rollover_total_calculation()
    sys.exit(0 if success else 1)
