/**
 * Serve Command
 *
 * 启动 HTTP Server
 */

import type { Command } from 'commander';

export function registerServeCommand(program: Command): void {
  program
    .command('serve')
    .description('Start the AI Assistant server')
    .option('-p, --port <port>', 'Port to listen on', '3000')
    .option('-H, --host <host>', 'Host to bind to', '127.0.0.1')
    .option('--auth', 'Enable authentication')
    .option('--no-auth', 'Disable authentication')
    .option('-t, --token <token>', 'Set authentication token')
    .action(async (options) => {
      const { port, host, auth, token } = options;

      // 动态导入 server 模块
      const { app, websocket, startServer } = await import('@ai-assistant/server');

      // 初始化并打印启动信息
      await startServer({
        port: parseInt(port, 10),
        host,
        auth,
        token,
      });

      // 启动 Bun 服务器
      const server = Bun.serve({
        port: parseInt(port, 10),
        hostname: host,
        fetch: app.fetch,
        websocket,
      });

      console.log(`Server running at http://${host}:${port}`);

      // 优雅关闭
      process.on('SIGINT', () => {
        console.log('\nShutting down server...');
        server.stop();
        process.exit(0);
      });

      process.on('SIGTERM', () => {
        console.log('\nShutting down server...');
        server.stop();
        process.exit(0);
      });
    });
}
