from __future__ import annotations

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from loguru import logger

from backend.app.core.config import load_config
from backend.app.scraper.runner import scrape_all

scheduler = BackgroundScheduler(timezone=load_config().scrape.timezone)
"""Scheduler interne APScheduler, prêt à déclencher scrape_all selon la config."""


def start_scheduler() -> None:
    if scheduler.running:
        return

    config = load_config()
    interval = config.scrape.interval_minutes
    scheduler.add_job(
        scrape_all,
        trigger=IntervalTrigger(minutes=interval),
        id="scheduled-scrape-all",
        replace_existing=True,
        next_run_time=None,
    )
    scheduler.start()
    logger.info("Scheduler démarré avec un intervalle de %s minutes", interval)
