import os, json
from pathlib import Path
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from .scrapers.runner import run_all

CONFIG = Path("config/schedule.json")
scheduler: BackgroundScheduler | None = None

def scheduler_get() -> str:
    cron = "0 3 * * *"
    if CONFIG.exists():
        cron = json.loads(CONFIG.read_text()).get("cron", cron)
    return cron

def scheduler_set(cron: str) -> None:
    CONFIG.parent.mkdir(parents=True, exist_ok=True)
    CONFIG.write_text(json.dumps({"cron": cron}))
    global scheduler
    if scheduler:
        scheduler.remove_all_jobs()
        scheduler.add_job(run_all, CronTrigger.from_crontab(cron), id="daily-run")

def scheduler_start():
    global scheduler
    if scheduler:
        return
    scheduler = BackgroundScheduler(timezone=os.getenv("TZ", "America/Chicago"))
    scheduler.start()
    scheduler_set(scheduler_get())
