"""
Test script to verify the pre_save signal is working
"""
import os
import django

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

from decimal import Decimal
from loans.models import Loan
from django.contrib.auth import get_user_model

User = get_user_model()

# Get any loan to test with
loan = Loan.objects.filter(status='active').first()

if not loan:
    print("No active loans found to test with")
    exit(1)

print(f"Testing with loan: {loan.loan_number}")
print(f"\nBefore edit:")
print(f"  Principal: KES {loan.principal_amount}")
print(f"  Interest: KES {loan.interest_amount}")
print(f"  Processing Fee: KES {loan.processing_fee}")
print(f"  Total Amount: KES {loan.total_amount}")

# Save original values to restore later
original_principal = loan.principal_amount
original_interest = loan.interest_amount
original_processing_fee = loan.processing_fee
original_total = loan.total_amount

# Make a small change to test
new_interest = loan.interest_amount + Decimal('100.00')
loan.interest_amount = new_interest

print(f"\nChanging interest to: KES {new_interest}")
print("Saving loan...")

# Save the loan
loan.save()

# Refresh from database
loan.refresh_from_db()

print(f"\nAfter save:")
print(f"  Principal: KES {loan.principal_amount}")
print(f"  Interest: KES {loan.interest_amount}")
print(f"  Processing Fee: KES {loan.processing_fee}")
print(f"  Total Amount: KES {loan.total_amount}")

expected_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
print(f"\nExpected Total: KES {expected_total}")
print(f"Actual Total: KES {loan.total_amount}")

if loan.total_amount == expected_total:
    print("\n✅ SUCCESS: Signal is working! Total amount recalculated correctly!")
else:
    print(f"\n❌ FAILED: Signal not working. Difference: KES {loan.total_amount - expected_total}")

# Restore original values
print("\nRestoring original values...")
loan.principal_amount = original_principal
loan.interest_amount = original_interest
loan.processing_fee = original_processing_fee
loan.save()
loan.refresh_from_db()

print(f"Restored total: KES {loan.total_amount}")
print(f"Original total: KES {original_total}")
