"""
fix_amount_paid_cache.py
-------------------------
Rebuilds _amount_paid_cache for every loan from the actual sum of its
repayment records. This fixes loans where the cache got out of sync
(e.g. repayments were inserted directly into the DB, the signal failed,
or the rollover process left the cache stale).

Also fixes outstanding_balance and loan status where needed.

Run on the server: python3 fix_amount_paid_cache.py
"""
import sys, os

PROJECT_ROOT = '/home/xygbfpsg/phingrazuri'
sys.path.insert(0, PROJECT_ROOT)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
os.environ.setdefault('DB_NAME',     'xygbfpsg_loans')
os.environ.setdefault('DB_USER',     'xygbfpsg_graz')
os.environ.setdefault('DB_PASSWORD', 'j.ez-xy6##y.rllB')
os.environ.setdefault('DB_HOST',     'localhost')
os.environ.setdefault('DB_PORT',     '3306')
import django
django.setup()

from decimal import Decimal
from django.db import connection
from django.db.models import Sum
from loans.models import Loan, Repayment

print("=" * 65)
print("  fix_amount_paid_cache.py")
print("=" * 65)

loans = Loan.objects.filter(is_deleted=False).select_related(
    'application__loan_product'
)

fixed = 0
already_ok = 0
status_fixed = 0

print(f"\nChecking {loans.count()} loan(s)...\n")
print(f"  {'Loan #':<22}  {'Cache':>12}  {'Actual':>12}  {'Offset':>12}  {'Net Paid':>10}  Action")
print("  " + "-" * 80)

for loan in loans:
    actual_sum = Repayment.objects.filter(loan=loan).aggregate(
        t=Sum('amount')
    )['t'] or Decimal('0.00')
    actual_sum = Decimal(str(actual_sum))
    cached     = Decimal(str(loan._amount_paid_cache))
    offset     = Decimal(str(loan.rollover_payment_offset or 0))
    net_paid   = actual_sum - offset

    if abs(cached - actual_sum) > Decimal('0.01'):
        action = f"FIX cache {cached:,.0f}→{actual_sum:,.0f}"

        # Update cache directly (bypass signal to avoid recursion)
        with connection.cursor() as cur:
            cur.execute(
                "UPDATE loans SET amount_paid=%s WHERE id=%s",
                [str(actual_sum), str(loan.id)]
            )
        connection.connection.commit()

        # Reload and check if status needs updating
        loan.refresh_from_db()
        if loan.status == 'active' and net_paid >= loan.principal_amount:
            with connection.cursor() as cur:
                cur.execute(
                    "UPDATE loans SET status='paid' WHERE id=%s",
                    [str(loan.id)]
                )
            connection.connection.commit()
            action += "  → status=paid"
            status_fixed += 1

        fixed += 1
        print(f"  {loan.loan_number:<22}  {cached:>12,.2f}  {actual_sum:>12,.2f}  {offset:>12,.2f}  {net_paid:>10,.2f}  {action}")
    else:
        already_ok += 1

print(f"\n  Fixed: {fixed}  Already OK: {already_ok}  Status updated: {status_fixed}")
print(f"\n{'='*65}\n  Done.\n{'='*65}")
