#!/usr/bin/env bun
/**
 * AI Assistant Server Entry Point
 *
 * 独立运行的服务器入口，用于开发和测试
 *
 * Usage:
 *   bun run packages/server/src/bin/server.ts
 *   bun run packages/server/src/bin/server.ts --port 8080
 *   bun run packages/server/src/bin/server.ts --host 0.0.0.0 --port 3000
 *   bun run packages/server/src/bin/server.ts --auth --token mytoken
 */

import { app, websocket, startServer } from '../index.js';

// 解析命令行参数
function parseArgs(): { port: number; host: string; auth?: boolean; token?: string } {
  const args = process.argv.slice(2);
  let port = 3000;
  let host = '127.0.0.1';
  let auth: boolean | undefined;
  let token: string | undefined;

  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--port' || args[i] === '-p') {
      port = parseInt(args[i + 1], 10) || 3000;
      i++;
    } else if (args[i] === '--host' || args[i] === '-H') {
      host = args[i + 1] || '127.0.0.1';
      i++;
    } else if (args[i] === '--auth') {
      auth = true;
    } else if (args[i] === '--no-auth') {
      auth = false;
    } else if (args[i] === '--token' || args[i] === '-t') {
      token = args[i + 1];
      i++;
    } else if (args[i] === '--help' || args[i] === '-h') {
      console.log(`
AI Assistant Server

Usage:
  bun run server.ts [options]

Options:
  -p, --port <port>    Port to listen on (default: 3000)
  -H, --host <host>    Host to bind to (default: 127.0.0.1)
  --auth               Enable authentication
  --no-auth            Disable authentication
  -t, --token <token>  Set authentication token
  -h, --help           Show this help message

Examples:
  # Local development (no auth)
  bun run server.ts

  # Remote server with auth
  bun run server.ts --host 0.0.0.0 --auth

  # Custom token
  bun run server.ts --host 0.0.0.0 --token mysecrettoken
      `);
      process.exit(0);
    }
  }

  return { port, host, auth, token };
}

// 主函数
async function main() {
  const { port, host, auth, token } = parseArgs();

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

  // 启动 Bun 服务器
  const server = Bun.serve({
    port,
    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);
  });
}

main().catch((error) => {
  console.error('Failed to start server:', error);
  process.exit(1);
});
