import { loadProjectEnv } from '../lib/load-env.js';
const envResult = loadProjectEnv();
if (envResult.loaded) console.log(`[heartbeat] loaded env from ${envResult.file}`);
import { getDb } from '../lib/db.js';
import { appendAudit } from '../lib/runtime.js';
import { runHeartbeatWorkerLoop, runHeartbeatWorkerOnce } from '../lib/heartbeat-worker.js';

const workerId = process.env.HEARTBEAT_WORKER_ID || `heartbeat-${process.pid}`;
const intervalMs = Number(process.env.HEARTBEAT_WORKER_INTERVAL_MS || 30000);

try {
  getDb();
  if (process.env.HEARTBEAT_WORKER_ONCE === '1') {
    const result = await runHeartbeatWorkerOnce({ workerId });
    console.log(`[heartbeat] ${new Date().toISOString()} worked=${result.worked} status=${result.status || 'idle'}`);
    process.exit(result.ok ? 0 : 1);
  }
  appendAudit({ type: 'heartbeat.worker.start', summary: 'Heartbeat worker started', status: 'running', meta: { workerId, intervalMs } });
  await runHeartbeatWorkerLoop({ workerId, intervalMs });
} catch (error) {
  console.error(error);
  process.exit(1);
}
