"""
fix_old_loan_totals.py
======================
One-time script to fix all existing loans where total_amount was
incorrectly stored as (principal + interest + fee) under the old system.

Under the current accounting model, total_amount = principal_amount
because the company pre-deducts interest and processing fees before
disbursement. The customer repays exactly the principal_amount entered.

Run on production with:
    python manage.py shell < fix_old_loan_totals.py
  or:
    python manage.py runscript fix_old_loan_totals   (if django-extensions installed)
"""

import os
import django

# Allow running standalone (not needed when using manage.py shell)
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

from loans.models import Loan
from django.db.models import F

print("=" * 60)
print("Fixing old loan totals (total_amount → principal_amount)")
print("=" * 60)

# Find all loans where total_amount != principal_amount
bad_loans = Loan.objects.exclude(total_amount=F('principal_amount'))
count = bad_loans.count()

if count == 0:
    print("✅ No loans need fixing. All totals already equal principal.")
else:
    print(f"Found {count} loan(s) to fix:\n")
    for loan in bad_loans:
        old_total = loan.total_amount
        # Use queryset.update() to bypass the pre_save signal (direct DB write)
        Loan.objects.filter(pk=loan.pk).update(total_amount=loan.principal_amount)
        print(
            f"  ✔ {loan.loan_number:<20} "
            f"principal={loan.principal_amount:>12,.2f}  "
            f"old_total={old_total:>12,.2f}  "
            f"new_total={loan.principal_amount:>12,.2f}"
        )

    print(f"\n✅ Fixed {count} loan(s) successfully.")

print("=" * 60)
