/**
 * main.ts — single binary entry point for AAO.
 *
 * Dispatches on the `AAO_MODE` environment variable:
 *   - `worker` (default) → src/worker-bootstrap.ts  (full AAO server)
 *   - `gateway`          → src/gateway/bootstrap.ts (LLM Gateway only)
 *
 * Unknown modes exit 1 with a clear message rather than silently
 * defaulting, so a typo doesn't quietly run worker mode in a deploy
 * intended as a gateway-only box.
 *
 * Why a single binary: keeps build artefacts, version tagging, and ops
 * tooling identical across both deploy shapes. The cost is a small
 * dynamic import — gateway mode never loads better-sqlite3 / piece
 * runner / browser session manager / etc. unless someone explicitly
 * sets AAO_MODE=worker (or omits the variable).
 *
 * The legacy `node dist/index.js` path is preserved by src/index.ts
 * which just re-exports the worker startup function — existing
 * service managers and docker images keep working.
 */
import { logger } from './logger.js';

async function main(): Promise<void> {
  const mode = process.env['AAO_MODE'] ?? 'worker';
  // AAO_CONFIG env で config.yaml の path を override 可能 (両 mode 共通)。
  // 未設定なら従来通り 'config.yaml' (cwd 相対) を使う。
  const configPath = process.env['AAO_CONFIG'];
  switch (mode) {
    case 'worker': {
      const m = await import('./worker-bootstrap.js');
      await m.start(configPath ? { configPath } : undefined);
      break;
    }
    case 'gateway': {
      const m = await import('./gateway/bootstrap.js');
      await m.start(configPath ? { configPath } : undefined);
      break;
    }
    default:
      logger.error(`Unknown AAO_MODE: '${mode}' (expected 'worker' or 'gateway')`);
      process.exit(1);
  }
}

main().catch((err: unknown) => {
  logger.error(`Fatal error in mode=${process.env['AAO_MODE'] ?? 'worker'}: ${err instanceof Error ? err.stack ?? err.message : String(err)}`);
  process.exit(1);
});
