"""
Management command to check and auto-approve credit for eligible customers

Run with: python manage.py check_credit_eligibility
Run for specific business: python manage.py check_credit_eligibility --business-id=<uuid>
Dry run (no changes): python manage.py check_credit_eligibility --dry-run
"""

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Sum, Count
from decimal import Decimal
from apps.sales.models import Customer
from apps.business.models import Business


class Command(BaseCommand):
    help = 'Check all customers for credit eligibility and auto-approve qualified ones'

    def add_arguments(self, parser):
        parser.add_argument(
            '--business-id',
            type=str,
            help='Check customers for specific business only',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show eligible customers without approving credit',
        )
        parser.add_argument(
            '--min-sales',
            type=int,
            default=5,
            help='Minimum number of completed sales (default: 5)',
        )
        parser.add_argument(
            '--min-amount',
            type=float,
            default=50000.00,
            help='Minimum total purchase amount (default: 50000)',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        min_sales = options['min_sales']
        min_amount = Decimal(str(options['min_amount']))
        
        self.stdout.write(self.style.SUCCESS('Starting credit eligibility check...'))
        self.stdout.write(f"Criteria: {min_sales}+ sales, {min_amount}+ total purchases")
        
        if dry_run:
            self.stdout.write(self.style.WARNING('DRY RUN MODE - No changes will be made'))
        
        # Filter customers
        customers = Customer.objects.filter(
            is_active=True,
            credit_enabled=False  # Only check customers without credit
        ).select_related('business')
        
        if options['business_id']:
            try:
                business = Business.objects.get(id=options['business_id'])
                customers = customers.filter(business=business)
                self.stdout.write(f"Checking customers for business: {business.name}")
            except Business.DoesNotExist:
                raise CommandError(f"Business with id {options['business_id']} not found")
        
        total_checked = 0
        total_eligible = 0
        total_approved = 0
        
        self.stdout.write('\n' + '='*80)
        
        for customer in customers:
            total_checked += 1
            
            # Check eligibility
            if dry_run:
                # Manual check for dry run
                from apps.sales.models import Sale, SaleReturn
                
                sales_stats = Sale.objects.filter(
                    customer=customer,
                    status='COMPLETED'
                ).aggregate(
                    total_sales=Sum('total_amount'),
                    sale_count=Count('id')
                )
                
                total_sales = sales_stats['total_sales'] or Decimal('0')
                sale_count = sales_stats['sale_count'] or 0
                
                # Check return rate
                returns_total = SaleReturn.objects.filter(
                    original_sale__customer=customer
                ).aggregate(
                    total=Sum('total_refund_amount')
                )['total'] or Decimal('0')
                
                return_rate = (returns_total / total_sales * 100) if total_sales > 0 else 0
                
                is_eligible = (
                    sale_count >= min_sales and
                    total_sales >= min_amount and
                    return_rate <= 5
                )
                
                if is_eligible:
                    total_eligible += 1
                    calculated_limit = min(total_sales * Decimal('0.20'), Decimal('100000.00'))
                    
                    self.stdout.write(
                        self.style.SUCCESS(f"\n✓ ELIGIBLE: {customer.name} ({customer.phone})")
                    )
                    self.stdout.write(f"  Business: {customer.business.name}")
                    self.stdout.write(f"  Sales: {sale_count} | Total: KES {total_sales:,.2f}")
                    self.stdout.write(f"  Return Rate: {return_rate:.2f}%")
                    self.stdout.write(f"  Proposed Credit Limit: KES {calculated_limit:,.2f}")
            else:
                # Actually approve credit
                try:
                    success, message = customer.check_and_auto_enable_credit()
                    
                    if success:
                        total_eligible += 1
                        total_approved += 1
                        
                        self.stdout.write(
                            self.style.SUCCESS(f"\n✓ APPROVED: {customer.name} ({customer.phone})")
                        )
                        self.stdout.write(f"  Business: {customer.business.name}")
                        self.stdout.write(f"  Credit Limit: KES {customer.credit_limit:,.2f}")
                        self.stdout.write(f"  {message}")
                    else:
                        # Not eligible, show reason
                        if 'Need at least' in message or 'must be at least' in message:
                            pass  # Silent skip for common cases
                        else:
                            self.stdout.write(
                                self.style.WARNING(f"\n✗ NOT ELIGIBLE: {customer.name}")
                            )
                            self.stdout.write(f"  Reason: {message}")
                    
                except Exception as e:
                    self.stdout.write(
                        self.style.ERROR(f"\n✗ ERROR: {customer.name}")
                    )
                    self.stdout.write(f"  Error: {str(e)}")
        
        # Summary
        self.stdout.write('\n' + '='*80)
        self.stdout.write(self.style.SUCCESS('\nSUMMARY:'))
        self.stdout.write(f"Total Customers Checked: {total_checked}")
        self.stdout.write(f"Eligible for Credit: {total_eligible}")
        
        if not dry_run:
            self.stdout.write(self.style.SUCCESS(f"Successfully Approved: {total_approved}"))
        else:
            self.stdout.write(
                self.style.WARNING(
                    f"\nDRY RUN COMPLETE - Run without --dry-run to approve {total_eligible} customers"
                )
            )
        
        self.stdout.write('='*80 + '\n')