#!/usr/bin/env python3
"""
Fix amount_paid field for all loans by recalculating from actual repayments
"""

import os
import sys
import django
from decimal import Decimal

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection, transaction
from django.db.models import Sum
from loans.models import Loan

def fix_amount_paid_for_all_loans():
    """Recalculate amount_paid for all loans based on actual repayments"""
    print("Starting amount_paid recalculation for all loans...")
    
    updated_count = 0
    
    with transaction.atomic():
        # Get all loans that are not deleted
        loans = Loan.objects.filter(is_deleted=False)
        
        for loan in loans:
            # Calculate total repayments for this loan
            total_paid = loan.repayments.aggregate(
                total=Sum('amount')
            )['total'] or Decimal('0.00')
            
            # Check if amount_paid needs updating
            if loan.amount_paid != total_paid:
                old_amount = loan.amount_paid
                loan.amount_paid = total_paid
                
                # Update status if fully paid
                if loan.amount_paid >= loan.total_amount and loan.status == 'active':
                    loan.status = 'paid'
                
                loan.save()
                updated_count += 1
                
                print(f"Updated {loan.loan_number}: {old_amount} -> {total_paid}")
    
    print(f"\nCompleted! Updated {updated_count} loans.")
    return updated_count

def fix_specific_loan(loan_number):
    """Fix amount_paid for a specific loan"""
    try:
        loan = Loan.objects.get(loan_number=loan_number, is_deleted=False)
        
        # Calculate total repayments
        total_paid = loan.repayments.aggregate(
            total=Sum('amount')
        )['total'] or Decimal('0.00')
        
        old_amount = loan.amount_paid
        loan.amount_paid = total_paid
        
        # Update status if fully paid
        if loan.amount_paid >= loan.total_amount and loan.status == 'active':
            loan.status = 'paid'
        
        loan.save()
        
        print(f"Fixed {loan_number}: {old_amount} -> {total_paid}")
        return True
        
    except Loan.DoesNotExist:
        print(f"Loan {loan_number} not found")
        return False

if __name__ == '__main__':
    if len(sys.argv) > 1:
        # Fix specific loan
        loan_number = sys.argv[1]
        fix_specific_loan(loan_number)
    else:
        # Fix all loans
        fix_amount_paid_for_all_loans()