from apscheduler.schedulers.background import BackgroundScheduler

from app import models
from app.config import get_settings
from app.database import SessionLocal
from app.services.task_runner import TaskRunner
from app.utils.time_utils import split_cron


scheduler = BackgroundScheduler()


def start_scheduler() -> None:
    settings = get_settings()
    if scheduler.running:
        return
    cron_kwargs = split_cron(settings.schedule_cron)
    scheduler.configure(timezone=settings.schedule_timezone)
    scheduler.add_job(
        scheduled_scan,
        "cron",
        id="scheduled_feishu_scan",
        replace_existing=True,
        **cron_kwargs,
    )
    scheduler.start()


def scheduled_scan() -> None:
    import asyncio

    with SessionLocal() as db:
        runner = TaskRunner()
        asyncio.run(runner.run(db, task_type=models.TaskType.scheduled_scan))

