"""
APScheduler configuration for background tasks
"""
import logging
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.triggers.interval import IntervalTrigger
from django.conf import settings

logger = logging.getLogger(__name__)

# Configure executors
executors = {
    'default': ThreadPoolExecutor(20),
}

# Configure job defaults
job_defaults = {
    'coalesce': False,
    'max_instances': 3,
    'misfire_grace_time': 300,  # 5 minutes
}

# Create scheduler instance
scheduler = BackgroundScheduler(
    executors=executors,
    job_defaults=job_defaults,
    timezone=settings.TIME_ZONE
)

def start_scheduler():
    """Start the scheduler if not already running"""
    if not scheduler.running:
        scheduler.start()
        logger.info("APScheduler started")
        
def shutdown_scheduler():
    """Shutdown the scheduler gracefully"""
    if scheduler.running:
        scheduler.shutdown()
        logger.info("APScheduler shutdown")
