import { Command } from 'commander';
import { createServer } from 'vite';
import chalk from 'chalk';
import { logger } from 'z-utils';
import { getViteConfig } from '../config/vite.js';
/**
 * 开发服务命令
 */
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) => {
    try {
        await startDevServer(options);
    }
    catch (error) {
        logger.error(`启动开发服务器失败: ${error instanceof Error ? error.message : String(error)}`);
        process.exit(1);
    }
});
/**
 * 启动开发服务器
 */
async function startDevServer(options) {
    logger.info('启动开发服务器...');
    // 获取 Vite 配置
    const viteConfig = await getViteConfig(options);
    // 创建 Vite 服务器
    const server = await createServer(viteConfig);
    // 启动服务器
    const port = parseInt(options.port?.toString() || '3000');
    const host = options.host || 'localhost';
    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() {
    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';
}
//# sourceMappingURL=serve.js.map