from django.core.management.base import BaseCommand
from django.db.models import Sum
from loans.models import Loan, Repayment
from decimal import Decimal

class Command(BaseCommand):
    help = 'Recalculate amount_paid for all loans based on actual repayments'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--loan-number',
            type=str,
            help='Fix specific loan by loan number (e.g., LOAN-4A52BB)',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be updated without making changes',
        )
    
    def handle(self, *args, **options):
        loan_number = options.get('loan_number')
        dry_run = options.get('dry_run')
        
        if loan_number:
            loans = Loan.objects.filter(loan_number=loan_number)
            if not loans.exists():
                self.stdout.write(self.style.ERROR(f'Loan {loan_number} not found'))
                return
        else:
            loans = Loan.objects.all()
        
        updated_count = 0
        
        for loan in loans:
            # Calculate actual amount paid from repayments
            actual_amount_paid = Repayment.objects.filter(
                loan=loan
            ).aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
            
            current_amount_paid = loan.amount_paid or Decimal('0.00')
            
            if actual_amount_paid != current_amount_paid:
                self.stdout.write(
                    f'Loan {loan.loan_number}: '
                    f'Current: KES {current_amount_paid}, '
                    f'Actual: KES {actual_amount_paid}'
                )
                
                if not dry_run:
                    loan.amount_paid = actual_amount_paid
                    
                    # Update last payment date
                    last_repayment = Repayment.objects.filter(
                        loan=loan
                    ).order_by('-payment_date').first()
                    
                    if last_repayment:
                        loan.last_payment_date = last_repayment.payment_date
                    
                    # Update status if fully paid
                    total_amount = (loan.principal_amount or Decimal('0.00')) + \
                                 (loan.interest_amount or Decimal('0.00')) + \
                                 (loan.processing_fee or Decimal('0.00'))
                    
                    if actual_amount_paid >= total_amount and loan.status != 'paid':
                        loan.status = 'paid'
                        self.stdout.write(
                            self.style.SUCCESS(f'  → Status updated to PAID')
                        )
                    
                    loan.save()
                    updated_count += 1
                    
                    self.stdout.write(
                        self.style.SUCCESS(f'  → Updated to KES {actual_amount_paid}')
                    )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING('DRY RUN - No changes made. Remove --dry-run to apply changes.')
            )
        else:
            self.stdout.write(
                self.style.SUCCESS(f'Successfully updated {updated_count} loans')
            )