import { env } from './env';
import { startWorkerServer } from './server';
import { reconcileExistingBoxes } from './user-container';
import { startWorker } from './worker';

// Dev-only watchdog: the dev runner chain (turbo → with-env → dotenv → bash)
// doesn't always forward the stop signal to this leaf process, so on restart the
// worker can orphan and keep holding port 3921. Exit when our original parent
// goes away (we get reparented) or on a stop signal, so restarts stay clean.
// Never enabled in prod (gated on SPOON_AGENT_DEV_WATCHDOG).
if (env.devWatchdog) {
  // Bun caches `process.ppid`, so poll whether the original parent still exists
  // (signal 0 throws once it's gone) rather than comparing ppid.
  const parentPid = process.ppid;
  const watcher = setInterval(() => {
    try {
      process.kill(parentPid, 0);
    } catch {
      console.log('Dev parent exited; shutting down worker.');
      process.exit(0);
    }
  }, 1000);
  watcher.unref();
  for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {
    process.on(signal, () => process.exit(0));
  }
}

startWorkerServer();
await reconcileExistingBoxes();
await startWorker();
