import fs from 'fs/promises';
import path from 'path';
/**
 * 检测 Base Build 的构建模式
 */
export async function detectBuildMode(baseBuildDir) {
    // 1. 读取 index.html
    const indexPath = path.join(baseBuildDir, 'index.html');
    const html = await fs.readFile(indexPath, 'utf-8');
    // 2. 检测 import map
    const hasImportMap = html.includes('<script type="importmap">');
    if (hasImportMap) {
        // ESM 模式
        const importMapMatch = html.match(/<script type="importmap">\s*(\{[\s\S]*?\})\s*<\/script>/);
        const importMapContent = importMapMatch ? JSON.parse(importMapMatch[1]) : { imports: {} };
        return {
            mode: 'esm',
            engine: 'playcanvas', // 默认 PlayCanvas，从元数据文件读取时会覆盖
            buildTool: 'generic', // 检测已有产物，构建工具未知
            importMap: {
                id: 'detected',
                imports: importMapContent.imports || {},
            },
            entryPoint: 'js/index.mjs',
        };
    }
    // Classic 模式
    return {
        mode: 'classic',
        engine: 'playcanvas', // 默认 PlayCanvas，从元数据文件读取时会覆盖
        buildTool: 'generic', // 检测已有产物，构建工具未知
    };
}
/**
 * 解析 Import Map 为 Vite resolve.alias
 */
export function importMapToAlias(importMap, baseBuildDir) {
    const alias = {};
    for (const [key, value] of Object.entries(importMap)) {
        // 移除尾部斜杠
        const cleanKey = key.replace(/\/$/, '');
        const cleanValue = value.replace(/^\.\//, '');
        alias[cleanKey] = path.resolve(baseBuildDir, cleanValue);
    }
    return alias;
}
