"""
Run scheduled report jobs manually for testing

Usage:
    python manage.py run_report_job --list
    python manage.py run_report_job execute_scheduled_reports
    python manage.py run_report_job check_low_stock_all_businesses
"""

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


class Command(BaseCommand):
    help = 'Manually run scheduled report jobs for testing'

    def add_arguments(self, parser):
        parser.add_argument(
            'job_name',
            nargs='?',
            type=str,
            help='Name of the job to run'
        )
        parser.add_argument(
            '--list',
            action='store_true',
            help='List all available jobs'
        )
        parser.add_argument(
            '--days',
            type=int,
            default=90,
            help='Days to keep for cleanup_old_reports (default: 90)'
        )

    def handle(self, *args, **options):
        jobs = {
            'execute_scheduled_reports': {
                'func': execute_scheduled_reports,
                'description': 'Execute all scheduled reports that are due'
            },
            'send_weekly_reports': {
                'func': send_weekly_reports,
                'description': 'Send weekly reports to all businesses'
            },
            'cleanup_old_report_logs': {
                'func': cleanup_old_report_logs,
                'description': 'Clean up old report execution logs'
            },
            'generate_all_monthly_reports': {
                'func': generate_all_monthly_reports,
                'description': 'Generate monthly reports for all businesses'
            },
            'check_low_stock_all_businesses': {
                'func': check_low_stock_all_businesses,
                'description': 'Check and notify low stock for all businesses'
            },
            'check_warranty_expiry_all_businesses': {
                'func': check_warranty_expiry_all_businesses,
                'description': 'Check and notify warranty expiry for all businesses'
            },
            'cleanup_old_reports': {
                'func': cleanup_old_reports,
                'description': 'Clean up old generated reports',
                'kwargs': True
            }
        }

        # List all jobs
        if options['list']:
            self.stdout.write(self.style.SUCCESS('Available jobs:\n'))
            for job_name, job_info in jobs.items():
                self.stdout.write(f'  • {job_name}')
                self.stdout.write(f'    {job_info["description"]}\n')
            return

        # Run specific job
        job_name = options['job_name']
        if not job_name:
            self.stdout.write(self.style.ERROR('Error: Please provide a job name or use --list'))
            return

        if job_name not in jobs:
            self.stdout.write(self.style.ERROR(f'Error: Unknown job "{job_name}"'))
            self.stdout.write('Use --list to see available jobs')
            return

        job_info = jobs[job_name]
        self.stdout.write(self.style.WARNING(f'\n▶ Running: {job_name}'))
        self.stdout.write(f'  {job_info["description"]}\n')

        try:
            if job_info.get('kwargs'):
                job_info['func'](days_to_keep=options['days'])
            else:
                job_info['func']()
            
            self.stdout.write(self.style.SUCCESS(f'\n✓ {job_name} completed successfully!\n'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'\n✗ {job_name} failed!'))
            self.stdout.write(self.style.ERROR(f'Error: {str(e)}\n'))
            import traceback
            traceback.print_exc()