import fs from 'fs/promises';
import path from 'path';
function resolveSuggestedPhysicsEngine(use3dPhysics) {
    return use3dPhysics ? 'cannon' : 'p2';
}
/**
 * 检测 Base Build 是否使用 Ammo.js 及建议的替换引擎
 * 与 CLI 的 detectAmmoUsage 逻辑一致
 */
export async function detectAmmoUsage(baseBuildDir) {
    const configPath = path.join(baseBuildDir, 'config.json');
    let hasAmmo = false;
    let use3dPhysics = false;
    try {
        const configContent = await fs.readFile(configPath, 'utf-8');
        const configJson = JSON.parse(configContent);
        // 检查 application_properties.use3dPhysics
        use3dPhysics = Boolean(configJson.application_properties?.use3dPhysics);
        // 如果 use3dPhysics 未设置，通过检查场景内容来推断
        if (!use3dPhysics) {
            try {
                const files = await fs.readdir(baseBuildDir);
                for (const file of files) {
                    if (file.endsWith('.json') && !['config.json', 'manifest.json'].includes(file)) {
                        try {
                            const sceneContent = await fs.readFile(path.join(baseBuildDir, file), 'utf-8');
                            if (sceneContent.includes('"rigidbody"') ||
                                sceneContent.includes('"collision"') ||
                                sceneContent.includes('"joint"')) {
                                use3dPhysics = true;
                                break;
                            }
                        }
                        catch {
                            /* 忽略 */
                        }
                    }
                }
            }
            catch {
                /* 忽略 */
            }
        }
        if (configJson.assets) {
            for (const asset of Object.values(configJson.assets)) {
                const assetData = asset;
                const moduleName = String(assetData?.data?.moduleName ?? '').toLowerCase();
                const fileUrl = String(assetData?.file?.url ?? '').toLowerCase();
                if (moduleName.includes('ammo') || fileUrl.includes('ammo')) {
                    hasAmmo = true;
                    break;
                }
            }
        }
    }
    catch {
        /* 忽略解析失败 */
    }
    if (!hasAmmo) {
        try {
            const settingsPath = path.join(baseBuildDir, '__settings__.js');
            const settingsContent = await fs.readFile(settingsPath, 'utf-8');
            if (settingsContent.toLowerCase().includes('ammo')) {
                hasAmmo = true;
            }
        }
        catch {
            /* 忽略读取失败 */
        }
    }
    return {
        hasAmmo,
        suggestedEngine: resolveSuggestedPhysicsEngine(use3dPhysics),
        use3dPhysics,
    };
}
