"""
Django management command to fix loan total amounts

Usage:
    python manage.py fix_loan_totals
"""

from django.core.management.base import BaseCommand
from loans.models import Loan
from decimal import Decimal


class Command(BaseCommand):
    help = 'Fix loan total amounts where total_amount != principal + interest + processing_fee'

    def handle(self, *args, **options):
        self.stdout.write("=" * 80)
        self.stdout.write(self.style.SUCCESS("FIXING LOAN TOTAL AMOUNT CALCULATIONS"))
        self.stdout.write("=" * 80)
        self.stdout.write("")
        
        # Get all loans
        all_loans = Loan.objects.all()
        self.stdout.write(f"📊 Total loans to check: {all_loans.count()}")
        self.stdout.write("")
        
        fixed_count = 0
        already_correct = 0
        errors = []
        
        for loan in all_loans:
            try:
                # Calculate what the total SHOULD be
                correct_total = loan.principal_amount + loan.interest_amount + loan.processing_fee
                
                # Check if current total is incorrect
                if loan.total_amount != correct_total:
                    old_total = loan.total_amount
                    difference = correct_total - old_total
                    
                    self.stdout.write(self.style.WARNING(f"🔧 Fixing Loan {loan.loan_number}"))
                    self.stdout.write(f"   Borrower: {loan.borrower.get_full_name()}")
                    self.stdout.write(f"   Principal: KES {loan.principal_amount:,.2f}")
                    self.stdout.write(f"   Interest: KES {loan.interest_amount:,.2f}")
                    self.stdout.write(f"   Processing Fee: KES {loan.processing_fee:,.2f}")
                    self.stdout.write(self.style.ERROR(f"   ❌ OLD Total: KES {old_total:,.2f}"))
                    self.stdout.write(self.style.SUCCESS(f"   ✅ NEW Total: KES {correct_total:,.2f}"))
                    self.stdout.write(f"   📈 Difference: KES {difference:,.2f}")
                    self.stdout.write("")
                    
                    # Update the loan
                    loan.total_amount = correct_total
                    loan.save()
                    
                    fixed_count += 1
                else:
                    already_correct += 1
                    
            except Exception as e:
                error_msg = f"Error fixing loan {loan.loan_number}: {str(e)}"
                self.stdout.write(self.style.ERROR(f"❌ {error_msg}"))
                errors.append(error_msg)
                self.stdout.write("")
        
        self.stdout.write("=" * 80)
        self.stdout.write(self.style.SUCCESS("SUMMARY"))
        self.stdout.write("=" * 80)
        self.stdout.write(self.style.SUCCESS(f"✅ Loans fixed: {fixed_count}"))
        self.stdout.write(f"✓ Loans already correct: {already_correct}")
        
        if errors:
            self.stdout.write(self.style.ERROR(f"❌ Errors: {len(errors)}"))
            for error in errors:
                self.stdout.write(f"   - {error}")
        
        self.stdout.write("")
        self.stdout.write("=" * 80)
        self.stdout.write(self.style.SUCCESS("FIX COMPLETE!"))
        self.stdout.write("=" * 80)
