import { loadProjectEnv } from '../lib/load-env.js';
const envResult = loadProjectEnv();
if (envResult.loaded) console.log(`[cron] loaded env from ${envResult.file}`);
import { getDb } from '../lib/db.js';
import { cronDaemonTick, appendAudit } from '../lib/runtime.js';
const intervalMs = Number(process.env.CRON_DAEMON_INTERVAL_MS || 30000);
let stopped = false;
let lastTickAt = null;
async function tick() {
  getDb();
  const result = await cronDaemonTick({ lastTickAt, intervalMs });
  lastTickAt = Date.now();
  console.log(`[cron] ${new Date().toISOString()} executed=${result.executed}`);
  return result;
}
process.on('SIGINT',()=>{stopped=true; appendAudit({type:'cron.stop',summary:'Cron daemon stopped',status:'stopped'}); process.exit(0);});
process.on('SIGTERM',()=>{stopped=true; appendAudit({type:'cron.stop',summary:'Cron daemon stopped',status:'stopped'}); process.exit(0);});
try { await tick(); } catch (error) { console.error(error); process.exitCode = 1; }
if (process.env.CRON_DAEMON_ONCE === '1') process.exit(process.exitCode || 0);
appendAudit({type:'cron.start',summary:'Cron daemon started',status:'running',meta:{intervalMs}});
setInterval(()=>{ if(!stopped) tick().catch(e=>console.error(e)); }, intervalMs);
