# apps/banking/management/commands/sync_account_balances.py
from django.core.management.base import BaseCommand
from apps.banking.signals import sync_all_account_balances


class Command(BaseCommand):
    help = 'Synchronise les soldes de tous les comptes avec leurs transactions'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Affiche les changements sans les appliquer',
        )
        
        parser.add_argument(
            '--account-id',
            type=str,
            help='Synchroniser seulement un compte spécifique (par ID)',
        )

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('🚀 Démarrage de la synchronisation des soldes...'))
        
        if options['dry_run']:
            self.stdout.write(self.style.WARNING('⚠️ Mode DRY-RUN: aucun changement ne sera appliqué'))
        
        try:
            if options['account_id']:
                from apps.banking.models import Account
                from apps.banking.signals import recalculate_account_balance
                
                try:
                    account = Account.objects.get(id=options['account_id'])
                    old_balance = account.balance
                    
                    if not options['dry_run']:
                        new_balance = recalculate_account_balance(account)
                        self.stdout.write(
                            self.style.SUCCESS(
                                f'✅ Compte "{account.name}": {old_balance} → {new_balance} FCFA'
                            )
                        )
                    else:
                        # Calculer sans sauvegarder
                        from django.db.models import Sum
                        from apps.banking.models import Transaction
                        
                        incoming = Transaction.objects.filter(
                            to_account=account
                        ).aggregate(total=Sum('amount'))['total'] or 0
                        
                        outgoing = Transaction.objects.filter(
                            from_account=account
                        ).aggregate(total=Sum('amount'))['total'] or 0
                        
                        new_balance = incoming - outgoing
                        
                        self.stdout.write(
                            self.style.WARNING(
                                f'🔍 Compte "{account.name}": {old_balance} → {new_balance} FCFA (DRY-RUN)'
                            )
                        )
                        
                except Account.DoesNotExist:
                    self.stdout.write(
                        self.style.ERROR(f'❌ Compte avec ID "{options["account_id"]}" introuvable')
                    )
                    return
            else:
                if not options['dry_run']:
                    updated_count = sync_all_account_balances()
                    self.stdout.write(
                        self.style.SUCCESS(f'✅ Synchronisation terminée: {updated_count} compte(s) mis à jour')
                    )
                else:
                    # Mode dry-run pour tous les comptes
                    from apps.banking.models import Account, Transaction
                    from django.db.models import Sum
                    
                    self.stdout.write('🔍 Aperçu des changements (DRY-RUN):')
                    changes_count = 0
                    
                    for account in Account.objects.all():
                        incoming = Transaction.objects.filter(
                            to_account=account
                        ).aggregate(total=Sum('amount'))['total'] or 0
                        
                        outgoing = Transaction.objects.filter(
                            from_account=account
                        ).aggregate(total=Sum('amount'))['total'] or 0
                        
                        calculated_balance = incoming - outgoing
                        
                        if account.balance != calculated_balance:
                            self.stdout.write(
                                self.style.WARNING(
                                    f'   📊 {account.name}: {account.balance} → {calculated_balance} FCFA'
                                )
                            )
                            changes_count += 1
                        else:
                            self.stdout.write(
                                self.style.SUCCESS(f'   ✅ {account.name}: {calculated_balance} FCFA (correct)')
                            )
                    
                    self.stdout.write(
                        self.style.WARNING(f'🔍 {changes_count} compte(s) seraient mis à jour')
                    )
                    
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ Erreur lors de la synchronisation: {e}')
            )
