from django.core.management.base import BaseCommand
from apps.business.models import Business
from apps.reporting.tasks import send_test_report_email
from apps.reporting.models import ReportPreferences
import time

class Command(BaseCommand):
    help = 'Send weekly reports to all active businesses'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--email',
            type=str,
            help='Override recipient email (defaults to business owner email or preferences)',
        )
        parser.add_argument(
            '--business-id',
            type=str,
            help='Send to specific business ID only',
        )
    
    def handle(self, *args, **options):
        override_email = options.get('email')
        specific_business_id = options.get('business_id')
        
        # Get businesses to process
        if specific_business_id:
            businesses = Business.objects.filter(id=specific_business_id)
            if not businesses.exists():
                self.stdout.write(self.style.ERROR(f"❌ Business with ID {specific_business_id} not found!"))
                return
        else:
            businesses = Business.objects.filter(is_active=True)
        
        if not businesses.exists():
            self.stdout.write(self.style.ERROR("❌ No active businesses found!"))
            return
        
        self.stdout.write(self.style.SUCCESS(f"\n📊 Processing {businesses.count()} business(es)...\n"))
        
        queued_tasks = []
        skipped = []
        
        for business in businesses:
            self.stdout.write(f"Processing: {business.name}")
            
            # Get or create preferences
            prefs, created = ReportPreferences.objects.get_or_create(
                business=business,
                defaults={
                    'enabled': True,
                    'recipients': [business.owner.email] if business.owner and business.owner.email else []
                }
            )
            
            # Determine recipient email
            if override_email:
                recipient_email = override_email
            elif prefs.recipients:
                recipient_email = prefs.recipients[0]  # Use first recipient
            elif business.owner and business.owner.email:
                recipient_email = business.owner.email
            elif business.email:
                recipient_email = business.email
            else:
                self.stdout.write(self.style.WARNING(f"  ⚠️  No email found, skipping {business.name}"))
                skipped.append(business.name)
                continue
            
            # Queue the report
            try:
                result = send_test_report_email.delay(business.id, recipient_email)
                queued_tasks.append({
                    'business': business.name,
                    'email': recipient_email,
                    'task_id': result.id,
                    'result': result
                })
                self.stdout.write(self.style.SUCCESS(
                    f"  ✓ Queued for {recipient_email} (Task: {result.id})"
                ))
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"  ❌ Error: {str(e)}"))
                skipped.append(business.name)
        
        # Summary
        self.stdout.write("\n" + "="*60)
        self.stdout.write(self.style.SUCCESS(f"\n📧 SUMMARY"))
        self.stdout.write(f"Total Businesses: {businesses.count()}")
        self.stdout.write(self.style.SUCCESS(f"✓ Reports Queued: {len(queued_tasks)}"))
        
        if skipped:
            self.stdout.write(self.style.WARNING(f"⚠️  Skipped: {len(skipped)}"))
            for business_name in skipped:
                self.stdout.write(f"   - {business_name}")
        
        # Check status of queued tasks
        if queued_tasks:
            self.stdout.write("\n⏳ Checking task status...\n")
            time.sleep(3)  # Give tasks time to process
            
            completed = 0
            pending = 0
            failed = 0
            
            for task_info in queued_tasks:
                result = task_info['result']
                
                if result.ready():
                    if result.successful():
                        completed += 1
                        self.stdout.write(self.style.SUCCESS(
                            f"✓ {task_info['business']}: Sent to {task_info['email']}"
                        ))
                    else:
                        failed += 1
                        self.stdout.write(self.style.ERROR(
                            f"✗ {task_info['business']}: Failed - {result.info}"
                        ))
                else:
                    pending += 1
                    self.stdout.write(self.style.WARNING(
                        f"⏳ {task_info['business']}: Still processing ({result.state})"
                    ))
            
            self.stdout.write("\n" + "="*60)
            self.stdout.write(f"\n✅ Completed: {completed}")
            self.stdout.write(f"⏳ Pending: {pending}")
            if failed > 0:
                self.stdout.write(self.style.ERROR(f"❌ Failed: {failed}"))
            
            if pending > 0:
                self.stdout.write(self.style.WARNING(
                    f"\n💡 {pending} tasks still processing. Check Celery worker logs."
                ))
                self.stdout.write("\nTo check individual task status:")
                self.stdout.write("python manage.py shell")
                self.stdout.write(">>> from celery.result import AsyncResult")
                self.stdout.write(">>> result = AsyncResult('TASK_ID')")
                self.stdout.write(">>> print(result.state, result.info)")