import cron from "node-cron";
import { runDueAutomationTick } from "../lib/automation/engine";

let ticking = false;

async function tick() {
  if (ticking) {
    console.log("[automation] 上一輪尚未結束，跳過本次 tick");
    return;
  }
  ticking = true;
  const now = new Date();
  try {
    const results = await runDueAutomationTick(now);
    if (results.length > 0) {
      for (const r of results) {
        console.log(
          `[automation] ${r.taskType}: ${r.ok ? "OK" : "FAIL"} — ${r.summary}`
        );
      }
    }
  } catch (error) {
    console.error("[automation] tick 失敗：", error);
  } finally {
    ticking = false;
  }
}

function main() {
  console.log("[automation] 巡樓自動化排程已啟動，每分鐘檢查到點的規則…");
  console.log("[automation] 提醒：只有開啟『帳號總開關』且規則 enabled 的任務才會執行。");
  cron.schedule("* * * * *", tick);
}

main();
