import logging
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from .data_updater import update_all_plex_libraries_cache

log = logging.getLogger(__name__)
scheduler = BackgroundScheduler(daemon=True)

def init_scheduler():
    """初始化并启动定时任务调度器"""
    if scheduler.running:
        log.warning("调度器已在运行中。")
        return

    try:
        # 在这里添加你的定时任务
        scheduler.add_job(
            func=update_all_plex_libraries_cache,
            trigger='interval',
            hours=1,  # 每1小时执行一次
            id='update_plex_job',
            replace_existing=True
        )
        
        # TODO: 添加其他任务
        # scheduler.add_job(...)

        scheduler.start()
        log.info("定时任务调度器已启动。")

        # 确保在应用退出时能优雅地关闭调度器
        atexit.register(lambda: scheduler.shutdown())
    except Exception as e:
        log.error(f"启动调度器失败: {e}", exc_info=True)

