"""
Force send weekly reports - bypasses scheduling checks
Useful for testing and manual report delivery

Place this file at:
apps/reporting/management/commands/send_reports_now.py
"""
from django.core.management.base import BaseCommand
from apps.business.models import Business
from apps.reporting.tasks_sync import send_business_weekly_report, send_report_now
from apps.reporting.models import ReportPreferences
import logging

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Force send weekly reports to all businesses (bypass scheduling checks)'

    def add_arguments(self, parser):
        parser.add_argument(
            '--business-id',
            type=str,
            help='Send report for specific business ID only'
        )
        parser.add_argument(
            '--email',
            type=str,
            help='Override recipient email (for testing)'
        )

    def handle(self, *args, **options):
        business_id = options.get('business_id')
        override_email = options.get('email')
        
        if business_id:
            # Send for specific business
            try:
                businesses = [Business.objects.get(id=business_id)]
            except Business.DoesNotExist:
                self.stdout.write(
                    self.style.ERROR(f'Business {business_id} not found')
                )
                return
        else:
            # Send for all active businesses
            businesses = Business.objects.filter(is_active=True)
        
        sent_count = 0
        failed_count = 0
        skipped_count = 0
        
        self.stdout.write(
            self.style.WARNING(f'\nProcessing {len(businesses)} business(es)...\n')
        )
        
        for business in businesses:
            try:
                # Get or create preferences
                try:
                    prefs = business.report_preferences
                except:
                    self.stdout.write(
                        self.style.WARNING(
                            f'⚠ No preferences for {business.name}, creating defaults...'
                        )
                    )
                    prefs = ReportPreferences.objects.create(
                        business=business,
                        enabled=True,
                        recipients=[business.owner.email] if business.owner else [],
                        frequency='WEEKLY'
                    )
                
                # Check recipients
                recipients = prefs.recipients if prefs.recipients else []
                if override_email:
                    recipients = [override_email]
                
                if not recipients:
                    skipped_count += 1
                    self.stdout.write(
                        self.style.WARNING(
                            f'⊘ Skipped {business.name} - no recipients configured'
                        )
                    )
                    continue
                
                if not prefs.enabled and not override_email:
                    skipped_count += 1
                    self.stdout.write(
                        self.style.WARNING(
                            f'⊘ Skipped {business.name} - reports disabled'
                        )
                    )
                    continue
                
                self.stdout.write(f'📧 Sending report for {business.name}...')
                self.stdout.write(f'   Recipients: {", ".join(recipients)}')
                
                # Force send report (with override email if provided)
                if override_email:
                    result = send_report_now(business.id, [override_email])
                else:
                    result = send_business_weekly_report(business.id)
                
                if result.get('status') == 'sent':
                    sent_count += 1
                    self.stdout.write(
                        self.style.SUCCESS(f'   ✓ Successfully sent!\n')
                    )
                elif result.get('status') == 'skipped':
                    skipped_count += 1
                    self.stdout.write(
                        self.style.WARNING(
                            f'   ⊘ Skipped: {result.get("reason", "Unknown")}\n'
                        )
                    )
                else:
                    failed_count += 1
                    error = result.get('error', result.get('reason', 'Unknown error'))
                    self.stdout.write(
                        self.style.ERROR(f'   ✗ Failed: {error}\n')
                    )
                    
            except Exception as e:
                failed_count += 1
                self.stdout.write(
                    self.style.ERROR(f'   ✗ Error for {business.name}: {str(e)}\n')
                )
                logger.error(f'Error sending report for {business.name}', exc_info=True)
        
        # Summary
        self.stdout.write('\n' + '='*60)
        self.stdout.write(self.style.SUCCESS(f'✓ Sent: {sent_count}'))
        self.stdout.write(self.style.ERROR(f'✗ Failed: {failed_count}'))
        self.stdout.write(self.style.WARNING(f'⊘ Skipped: {skipped_count}'))
        self.stdout.write('='*60 + '\n')
        
        if sent_count > 0:
            self.stdout.write(
                self.style.SUCCESS(
                    'Check your email inbox (and spam folder) for the reports!'
                )
            )