from django.core.management.base import BaseCommand
from django.db import transaction
from loans.models import Repayment
from django.db.models import Count


class Command(BaseCommand):
    help = 'Fix duplicate receipt numbers in repayments'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be fixed without making changes',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        self.stdout.write("Checking for duplicate receipt numbers...")
        
        # Find duplicates
        duplicates = Repayment.objects.values('receipt_number').annotate(
            count=Count('receipt_number')
        ).filter(count__gt=1)
        
        if not duplicates:
            self.stdout.write(
                self.style.SUCCESS("No duplicate receipt numbers found!")
            )
            return
        
        self.stdout.write(f"Found {len(duplicates)} duplicate receipt numbers:")
        
        for dup in duplicates:
            receipt_number = dup['receipt_number']
            count = dup['count']
            self.stdout.write(f"  - {receipt_number}: {count} occurrences")
            
            # Get all repayments with this receipt number
            repayments = Repayment.objects.filter(
                receipt_number=receipt_number
            ).order_by('created_at')
            
            if dry_run:
                self.stdout.write(f"    Would keep first repayment (ID: {repayments.first().id})")
                for rep in repayments[1:]:
                    self.stdout.write(f"    Would renumber repayment ID: {rep.id}")
            else:
                # Keep the first one, renumber the rest
                with transaction.atomic():
                    for rep in repayments[1:]:
                        # Generate new receipt number
                        existing_numbers = set()
                        for receipt in Repayment.objects.values_list('receipt_number', flat=True):
                            if receipt and receipt.startswith('RCP-'):
                                try:
                                    num = int(receipt.split('-')[1])
                                    existing_numbers.add(num)
                                except (IndexError, ValueError):
                                    continue
                        
                        # Find next available number
                        next_num = 1
                        while next_num in existing_numbers:
                            next_num += 1
                        
                        old_receipt = rep.receipt_number
                        rep.receipt_number = f"RCP-{next_num:06d}"
                        rep.save()
                        
                        self.stdout.write(
                            f"    Renumbered repayment {rep.id}: {old_receipt} -> {rep.receipt_number}"
                        )
        
        if not dry_run:
            self.stdout.write(
                self.style.SUCCESS("Successfully fixed all duplicate receipt numbers!")
            )
        else:
            self.stdout.write(
                self.style.WARNING("Dry run completed. Use --dry-run=False to apply changes.")
            )