from django.core.management.base import BaseCommand
from apps.reporting.tasks_sync import (
    send_weekly_reports,
    generate_all_monthly_reports,
    cleanup_old_reports,
    check_low_stock_all_businesses,
    check_warranty_expiry_all_businesses
)
from datetime import datetime
import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Run scheduled report tasks'

    def add_arguments(self, parser):
        parser.add_argument(
            '--task',
            type=str,
            choices=['weekly', 'monthly', 'cleanup', 'low_stock', 'warranty'],
            required=True,
            help='Which task to run'
        )

    def handle(self, *args, **options):
        task = options['task']
        
        try:
            if task == 'weekly':
                result = send_weekly_reports()
                self.stdout.write(self.style.SUCCESS(f'Weekly reports: {result}'))
            
            elif task == 'monthly':
                result = generate_all_monthly_reports()
                self.stdout.write(self.style.SUCCESS(f'Monthly reports: {result}'))
            
            elif task == 'cleanup':
                result = cleanup_old_reports()
                self.stdout.write(self.style.SUCCESS(f'Cleanup: {result}'))
            
            elif task == 'low_stock':
                result = check_low_stock_all_businesses()
                self.stdout.write(self.style.SUCCESS(f'Low stock check: {result}'))
            
            elif task == 'warranty':
                result = check_warranty_expiry_all_businesses()
                self.stdout.write(self.style.SUCCESS(f'Warranty check: {result}'))
                
        except Exception as e:
            logger.error(f'Error running {task}: {str(e)}', exc_info=True)
            self.stdout.write(self.style.ERROR(f'Error: {str(e)}'))