from django.core.management.base import BaseCommand
from django.db.models import Sum
from loans.models import Repayment, Loan
from utils.models import Receipt
from decimal import Decimal

class Command(BaseCommand):
    help = 'Fix receipt balance calculations and create missing receipts'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be done without making changes',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        if dry_run:
            self.stdout.write(self.style.WARNING('DRY RUN MODE - No changes will be made'))
        
        # Get all loans with repayments
        loans_with_repayments = Loan.objects.filter(repayments__isnull=False).distinct()
        
        total_fixed = 0
        total_created = 0
        
        for loan in loans_with_repayments:
            self.stdout.write(f'Processing loan {loan.loan_number}...')
            
            # Get all repayments for this loan ordered by payment date
            repayments = loan.repayments.order_by('payment_date', 'created_at')
            
            running_paid = Decimal('0.00')
            
            for repayment in repayments:
                # Calculate correct balances for THIS specific repayment
                previous_balance = loan.total_amount - running_paid
                new_balance = previous_balance - repayment.amount
                
                # Update running total AFTER calculating balances
                running_paid += repayment.amount
                
                try:
                    # Try to get existing receipt
                    receipt = Receipt.objects.get(repayment=repayment)
                    
                    # Check if balance needs updating
                    if (receipt.previous_balance != previous_balance or 
                        receipt.new_balance != new_balance):
                        
                        if not dry_run:
                            receipt.previous_balance = previous_balance
                            receipt.new_balance = new_balance
                            receipt.save()
                        
                        self.stdout.write(
                            f'  Fixed receipt {receipt.receipt_number}: '
                            f'Previous: {receipt.previous_balance} -> {previous_balance}, '
                            f'New: {receipt.new_balance} -> {new_balance}'
                        )
                        total_fixed += 1
                        
                except Receipt.DoesNotExist:
                    # Create missing receipt with correct individual balances
                    if not dry_run:
                        Receipt.objects.create(
                            repayment=repayment,
                            loan=loan,
                            borrower=loan.borrower,
                            receipt_number=repayment.receipt_number,
                            amount_paid=repayment.amount,
                            payment_method=repayment.payment_method,
                            payment_date=repayment.payment_date,
                            previous_balance=previous_balance,
                            new_balance=new_balance,
                        )
                    
                    self.stdout.write(
                        f'  Created missing receipt {repayment.receipt_number} - '
                        f'Previous: {previous_balance}, New: {new_balance}'
                    )
                    total_created += 1
        
        self.stdout.write(
            self.style.SUCCESS(
                f'Completed! Fixed {total_fixed} receipts, created {total_created} missing receipts.'
            )
        )