import { Command } from 'commander';
import { createServer } from 'vite';
import chalk from 'chalk';
import { logger, FileUtils, type ServiceConfig } from 'z-utils';
import { getViteConfig } from '../config/vite.js';

// Commander 选项类型
interface ServeOptions {
  port?: string;
  host?: string;
  config?: string;
  mode?: string;
}

/**
 * 开发服务命令
 */
export const serveCommand = new Command('serve')
  .description('启动开发服务器')
  .option('-p, --port <port>', '端口号', '3000')
  .option('-h, --host <host>', '主机地址', 'localhost')
  .option('-c, --config <config>', '配置文件路径')
  .option('-m, --mode <mode>', '模式', 'development')
  .action(async (options: ServeOptions) => {
    try {
      // 转换选项类型
      const serviceConfig: ServiceConfig = {
        port: parseInt(options.port || '3000'),
        host: options.host || 'localhost',
        mode: (options.mode as 'development' | 'production' | 'test') || 'development',
        config: options.config,
        outDir: 'dist'
      };
      await startDevServer(serviceConfig);
    } catch (error) {
      logger.error(`启动开发服务器失败: ${error instanceof Error ? error.message : String(error)}`);
      process.exit(1);
    }
  });

/**
 * 启动开发服务器
 */
async function startDevServer(options: ServiceConfig): Promise<void> {
  logger.info('启动开发服务器...');
  
  // 获取 Vite 配置
  const viteConfig = await getViteConfig(options);
  
  // 创建 Vite 服务器
  const server = await createServer(viteConfig);
  
  // 启动服务器
  const port = options.port;
  const host = options.host;
  
  await server.listen(port, host);
  
  const url = `http://${host}:${port}`;
  
  logger.success(`开发服务器已启动:`);
  console.log();
  console.log(`  ${chalk.cyan('Local:')}   ${chalk.underline(url)}`);
  console.log(`  ${chalk.cyan('Network:')} ${chalk.underline(`http://${getNetworkAddress()}:${port}`)}`);
  console.log();
  
  // 优雅关闭
  process.on('SIGINT', async () => {
    logger.info('正在关闭开发服务器...');
    await server.close();
    process.exit(0);
  });
  
  process.on('SIGTERM', async () => {
    logger.info('正在关闭开发服务器...');
    await server.close();
    process.exit(0);
  });
}

/**
 * 获取网络地址
 */
function getNetworkAddress(): string {
  const { networkInterfaces } = require('os');
  const nets = networkInterfaces();
  
  for (const name of Object.keys(nets)) {
    for (const net of nets[name]) {
      if (net.family === 'IPv4' && !net.internal) {
        return net.address;
      }
    }
  }
  
  return 'localhost';
}
