"""
Management command to test the scheduler
Place in: apps/reporting/management/commands/test_scheduler.py

Usage:
    python manage.py test_scheduler
"""

from django.core.management.base import BaseCommand
from apps.reporting.scheduler import start_scheduler
import time


class Command(BaseCommand):
    help = 'Test the APScheduler setup'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting scheduler test...'))
        
        try:
            scheduler = start_scheduler()
            
            self.stdout.write(self.style.SUCCESS('Scheduler started successfully!'))
            self.stdout.write('\nScheduled jobs:')
            
            for job in scheduler.get_jobs():
                self.stdout.write(f'  - {job.id}: {job.name}')
                self.stdout.write(f'    Next run: {job.next_run_time}')
                self.stdout.write(f'    Trigger: {job.trigger}')
                self.stdout.write('')
            
            self.stdout.write(self.style.WARNING('\nScheduler is running. Press Ctrl+C to stop.'))
            
            # Keep the command running
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                self.stdout.write(self.style.SUCCESS('\nShutting down scheduler...'))
                scheduler.shutdown()
                self.stdout.write(self.style.SUCCESS('Scheduler stopped.'))
                
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error: {str(e)}'))
            import traceback
            traceback.print_exc()