import fs from 'fs/promises';
import path from 'path';
import { build as viteBuild } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';
import { viteSourceBuilderPlugin } from '../vite/plugin-source-builder.js';
import { loadPlayCanvasProject } from '../loaders/playcanvas-loader.js';
import { BuildStateManager } from '../state/index.js';
import { BuildAnalyzer } from '../analyzers/build-analyzer.js';
/**
 * PlayCanvas 引擎适配器
 * 负责 PlayCanvas 项目的 Base Build（生成可运行的多文件构建产物）
 */
export class PlayCanvasAdapter {
    constructor(projectDir, options) {
        this.projectDir = projectDir;
        this.options = options;
        this.stateManager = new BuildStateManager(projectDir, options.outputDir);
        console.log(`[PlayCanvasAdapter] 初始化: projectDir=${projectDir}, outputDir=${options.outputDir}`);
    }
    /**
     * 执行 PlayCanvas 基础构建
     */
    async baseBuild() {
        // 开始构建阶段
        this.stateManager.startStage('base-build', {
            selectedScenes: this.options.selectedScenes,
            analyze: this.options.analyze,
            clean: this.options.clean,
            engine: 'playcanvas',
        });
        // 检测项目类型
        const projectType = await this.detectProjectType();
        let result;
        if (projectType === 'official-build') {
            // 官方构建产物 - 直接复制并验证
            result = await this.buildFromOfficial();
        }
        else {
            // 源代码格式（PlayCanvas 或 PlayCraft）- 使用 Vite 生成构建产物
            const formatName = projectType === 'playcraft' ? 'PlayCraft' : 'PlayCanvas';
            console.log(`[PlayCanvasAdapter] 检测到 ${formatName} 源代码格式，使用 Vite 构建...`);
            result = await this.buildFromSource();
        }
        // 保存构建元数据（包含引擎类型）
        await this.saveBuildMetadata(result.metadata);
        // 记录构建产物
        await this.recordBuildOutput(result);
        // 结束构建阶段
        this.stateManager.endStage();
        // 生成分析报告（如果启用）
        if (this.options.analyze) {
            await this.stateManager.saveState();
            await this.generateAnalysisReport();
        }
        return result;
    }
    /**
     * 保存构建元数据到输出目录
     */
    async saveBuildMetadata(metadata) {
        const metadataPath = path.join(this.options.outputDir, '.build-metadata.json');
        await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf-8');
        console.log('[PlayCanvasAdapter] 构建元数据已保存（引擎: playcanvas）');
    }
    /**
     * 检测项目类型
     */
    async detectProjectType() {
        // 1. 检查是否是官方构建产物
        const buildIndicators = [
            path.join(this.projectDir, 'index.html'),
            path.join(this.projectDir, 'config.json'),
        ];
        try {
            await fs.access(buildIndicators[0]);
            await fs.access(buildIndicators[1]);
            return 'official-build';
        }
        catch {
            // 2. 检查是否是 PlayCraft 项目格式
            const manifestPath = path.join(this.projectDir, 'manifest.json');
            try {
                await fs.access(manifestPath);
                const manifestContent = await fs.readFile(manifestPath, 'utf-8');
                const manifest = JSON.parse(manifestContent);
                if (manifest.format === 'playcraft' || Array.isArray(manifest.assets)) {
                    return 'playcraft';
                }
            }
            catch {
                // manifest.json 不存在或格式不对
            }
            // 3. 默认视为源代码项目
            return 'source';
        }
    }
    /**
     * 检测是否为 ESM 格式项目
     */
    async detectESMFormat() {
        const esmIndicators = [
            path.join(this.projectDir, 'js/index.mjs'),
            path.join(this.projectDir, 'esm-scripts'),
        ];
        for (const indicator of esmIndicators) {
            try {
                await fs.access(indicator);
                return true;
            }
            catch {
                // 继续检查下一个
            }
        }
        return false;
    }
    /**
     * 从 PlayCraft 项目中加载 Import Map
     * PlayCraft 的 import map 存储在 assets/Import Map.json 中，
     * 其 asset ID 在 manifest.settings.importMap 中引用
     */
    async loadPlayCraftImportMap() {
        try {
            // 直接尝试读取 assets/Import Map.json
            const importMapPath = path.join(this.projectDir, 'assets', 'Import Map.json');
            const content = await fs.readFile(importMapPath, 'utf-8');
            const importMapContent = JSON.parse(content);
            if (importMapContent.imports) {
                console.log(`[PlayCanvasAdapter] 加载了 PlayCraft Import Map: ${Object.keys(importMapContent.imports).length} 个映射`);
                return {
                    id: 'playcraft-import-map',
                    content: importMapContent,
                };
            }
        }
        catch {
            // Import Map 文件不存在或格式不对
        }
        // 尝试从 manifest 中读取 importMap asset ID，再从 assets.json 查找
        try {
            const manifestContent = await fs.readFile(path.join(this.projectDir, 'manifest.json'), 'utf-8');
            const manifest = JSON.parse(manifestContent);
            const importMapId = manifest.settings?.importMap;
            if (importMapId) {
                const assetsJsonPath = path.join(this.projectDir, 'assets', 'assets.json');
                const assetsContent = await fs.readFile(assetsJsonPath, 'utf-8');
                const assets = JSON.parse(assetsContent);
                const importMapAsset = assets[String(importMapId)];
                if (importMapAsset?.file?.url) {
                    // 尝试从本地路径读取
                    const url = importMapAsset.file.url;
                    if (!url.startsWith('/api/') && !url.startsWith('http')) {
                        const filePath = path.join(this.projectDir, url);
                        const content = await fs.readFile(filePath, 'utf-8');
                        const importMapContent = JSON.parse(content);
                        if (importMapContent.imports) {
                            console.log(`[PlayCanvasAdapter] 从 assets.json 加载 Import Map: ${Object.keys(importMapContent.imports).length} 个映射`);
                            return {
                                id: String(importMapId),
                                content: importMapContent,
                            };
                        }
                    }
                }
            }
        }
        catch {
            // 无法从 manifest/assets.json 加载
        }
        return undefined;
    }
    /**
     * 从官方构建产物构建
     */
    async buildFromOfficial() {
        await this.validateOfficialBuild();
        await fs.mkdir(this.options.outputDir, { recursive: true });
        const files = await this.copyBuildFiles();
        const metadata = await this.detectBuildModeFromOutput();
        return {
            outputDir: this.options.outputDir,
            metadata,
            files,
        };
    }
    /**
     * 从输出目录检测构建模式
     */
    async detectBuildModeFromOutput() {
        const indexPath = path.join(this.options.outputDir, 'index.html');
        try {
            const html = await fs.readFile(indexPath, 'utf-8');
            const hasImportMap = html.includes('<script type="importmap">');
            if (hasImportMap) {
                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',
                    buildTool: 'playcanvas-native',
                    importMap: {
                        id: 'detected',
                        imports: importMapContent.imports || {},
                    },
                    entryPoint: 'js/index.mjs',
                };
            }
        }
        catch {
            // 忽略错误，返回 Classic 模式
        }
        return {
            mode: 'classic',
            engine: 'playcanvas',
            buildTool: 'playcanvas-native',
        };
    }
    /**
     * 验证官方构建产物
     */
    async validateOfficialBuild() {
        const isESM = await this.detectESMFormat();
        const requiredFiles = isESM
            ? ['index.html', 'config.json']
            : ['index.html', 'config.json', '__start__.js'];
        const missingFiles = [];
        for (const file of requiredFiles) {
            try {
                await fs.access(path.join(this.projectDir, file));
            }
            catch {
                missingFiles.push(file);
            }
        }
        if (missingFiles.length > 0) {
            const formatType = isESM ? 'ESM' : 'Classic';
            throw new Error(`官方构建产物缺少必需文件: ${missingFiles.join(', ')}\n` +
                `检测到 ${formatType} 格式，请确保项目目录包含完整的构建产物。`);
        }
    }
    /**
     * 复制构建文件到输出目录
     */
    async copyBuildFiles() {
        const files = {
            html: '',
            engine: null,
            config: '',
            settings: null,
            modules: null,
            start: '',
            scenes: [],
            assets: [],
        };
        // 复制 index.html
        const htmlPath = path.join(this.projectDir, 'index.html');
        const outputHtmlPath = path.join(this.options.outputDir, 'index.html');
        await fs.copyFile(htmlPath, outputHtmlPath);
        files.html = outputHtmlPath;
        // 复制 config.json
        const configPath = path.join(this.projectDir, 'config.json');
        const outputConfigPath = path.join(this.options.outputDir, 'config.json');
        await fs.copyFile(configPath, outputConfigPath);
        files.config = outputConfigPath;
        const configContent = await fs.readFile(configPath, 'utf-8');
        const configJson = JSON.parse(configContent);
        const isESM = await this.detectESMFormat();
        // 复制 __start__.js（Classic 格式必需）
        if (!isESM) {
            const startPath = path.join(this.projectDir, '__start__.js');
            const outputStartPath = path.join(this.options.outputDir, '__start__.js');
            try {
                await fs.copyFile(startPath, outputStartPath);
                files.start = outputStartPath;
            }
            catch {
                console.warn('[PlayCanvasAdapter] 警告: 无法复制 __start__.js');
            }
        }
        // 复制 __settings__.js
        const settingsPath = path.join(this.projectDir, '__settings__.js');
        try {
            await fs.access(settingsPath);
            const outputSettingsPath = path.join(this.options.outputDir, '__settings__.js');
            await fs.copyFile(settingsPath, outputSettingsPath);
            files.settings = outputSettingsPath;
        }
        catch {
            // __settings__.js 不是必需的
        }
        // 复制 __modules__.js
        const modulesPath = path.join(this.projectDir, '__modules__.js');
        try {
            await fs.access(modulesPath);
            const outputModulesPath = path.join(this.options.outputDir, '__modules__.js');
            await fs.copyFile(modulesPath, outputModulesPath);
            files.modules = outputModulesPath;
        }
        catch {
            // __modules__.js 不是必需的
        }
        // 复制 PlayCanvas Engine
        const engineNames = [
            'playcanvas-stable.min.js',
            'playcanvas.min.js',
            '__lib__.js',
        ];
        for (const engineName of engineNames) {
            const enginePath = path.join(this.projectDir, engineName);
            try {
                await fs.access(enginePath);
                const outputEnginePath = path.join(this.options.outputDir, engineName);
                await fs.copyFile(enginePath, outputEnginePath);
                files.engine = outputEnginePath;
                break;
            }
            catch {
                // 继续尝试下一个
            }
        }
        // 复制场景文件
        if (configJson.scenes && Array.isArray(configJson.scenes)) {
            for (const scene of configJson.scenes) {
                if (scene.url && !scene.url.startsWith('data:')) {
                    const scenePath = path.join(this.projectDir, scene.url);
                    try {
                        await fs.access(scenePath);
                        const sceneDir = path.dirname(scene.url);
                        if (sceneDir && sceneDir !== '.') {
                            const outputSceneDir = path.join(this.options.outputDir, sceneDir);
                            await fs.mkdir(outputSceneDir, { recursive: true });
                        }
                        const outputScenePath = path.join(this.options.outputDir, scene.url);
                        await fs.copyFile(scenePath, outputScenePath);
                        files.scenes.push(outputScenePath);
                    }
                    catch {
                        console.warn(`[PlayCanvasAdapter] 警告: 场景文件不存在: ${scene.url}`);
                    }
                }
            }
        }
        // 复制资产文件
        if (configJson.assets) {
            const assetsDir = path.join(this.options.outputDir, 'files');
            await fs.mkdir(assetsDir, { recursive: true });
            for (const [, assetData] of Object.entries(configJson.assets)) {
                const asset = assetData;
                if (asset.file && asset.file.url && !asset.file.url.startsWith('data:')) {
                    const assetPath = path.join(this.projectDir, asset.file.url);
                    try {
                        await fs.access(assetPath);
                        const assetDir = path.dirname(asset.file.url);
                        if (assetDir && assetDir !== '.') {
                            const outputAssetDir = path.join(this.options.outputDir, assetDir);
                            await fs.mkdir(outputAssetDir, { recursive: true });
                        }
                        const outputAssetPath = path.join(this.options.outputDir, asset.file.url);
                        await fs.copyFile(assetPath, outputAssetPath);
                        files.assets.push(outputAssetPath);
                    }
                    catch {
                        // 资产文件可能不存在
                    }
                }
            }
        }
        // 复制其他目录
        await this.copyAdditionalDirectories(files);
        return files;
    }
    /**
     * 复制其他必要的目录
     */
    async copyAdditionalDirectories(files) {
        // files/ 目录
        const filesDir = path.join(this.projectDir, 'files');
        try {
            const stat = await fs.stat(filesDir);
            if (stat.isDirectory()) {
                const outputFilesDir = path.join(this.options.outputDir, 'files');
                await this.copyDirectory(filesDir, outputFilesDir);
            }
        }
        catch {
            // files/ 目录可能不存在
        }
        // styles.css
        const stylesPath = path.join(this.projectDir, 'styles.css');
        try {
            await fs.access(stylesPath);
            const outputStylesPath = path.join(this.options.outputDir, 'styles.css');
            await fs.copyFile(stylesPath, outputStylesPath);
        }
        catch {
            // styles.css 可能不存在
        }
        // manifest.json
        const manifestPath = path.join(this.projectDir, 'manifest.json');
        try {
            await fs.access(manifestPath);
            const outputManifestPath = path.join(this.options.outputDir, 'manifest.json');
            await fs.copyFile(manifestPath, outputManifestPath);
        }
        catch {
            // manifest.json 可能不存在
        }
        // js/ 目录（ESM）
        const jsDir = path.join(this.projectDir, 'js');
        try {
            const stat = await fs.stat(jsDir);
            if (stat.isDirectory()) {
                const outputJsDir = path.join(this.options.outputDir, 'js');
                await this.copyDirectory(jsDir, outputJsDir);
            }
        }
        catch {
            // js/ 目录可能不存在
        }
        // esm-scripts/ 目录（ESM）
        const esmScriptsDir = path.join(this.projectDir, 'esm-scripts');
        try {
            const stat = await fs.stat(esmScriptsDir);
            if (stat.isDirectory()) {
                const outputEsmScriptsDir = path.join(this.options.outputDir, 'esm-scripts');
                await this.copyDirectory(esmScriptsDir, outputEsmScriptsDir);
            }
        }
        catch {
            // esm-scripts/ 目录可能不存在
        }
    }
    /**
     * 递归复制目录
     */
    async copyDirectory(src, dest) {
        await fs.mkdir(dest, { recursive: true });
        const entries = await fs.readdir(src, { withFileTypes: true });
        for (const entry of entries) {
            const srcPath = path.join(src, entry.name);
            const destPath = path.join(dest, entry.name);
            if (entry.isDirectory()) {
                await this.copyDirectory(srcPath, destPath);
            }
            else {
                await fs.copyFile(srcPath, destPath);
            }
        }
    }
    /**
     * 从源代码构建（使用 Vite）
     */
    async buildFromSource() {
        console.log('[PlayCanvasAdapter] 使用 Vite 从源代码构建...');
        let buildMode = 'classic';
        let importMap = undefined;
        try {
            console.log('[PlayCanvasAdapter] 正在加载项目配置...');
            // 先检查是否是 PlayCraft 格式（根目录没有 project.json）
            const manifestPath = path.join(this.projectDir, 'manifest.json');
            let isPlayCraft = false;
            try {
                const manifestContent = await fs.readFile(manifestPath, 'utf-8');
                const manifest = JSON.parse(manifestContent);
                isPlayCraft = manifest.format === 'playcraft' || Array.isArray(manifest.assets);
            }
            catch {
                // manifest.json 不存在
            }
            if (!isPlayCraft) {
                // PlayCanvas 原生格式：从 project.json 加载以检测 ESM 模式
                const projectConfig = await loadPlayCanvasProject(this.projectDir);
                buildMode = projectConfig.importMap ? 'esm' : 'classic';
                importMap = projectConfig.importMap;
            }
            else {
                // PlayCraft 格式：先加载 Import Map，再决定构建模式
                // Import Map 存在意味着项目使用 ESM 模式（与 PlayCanvas 格式检测逻辑一致）
                importMap = await this.loadPlayCraftImportMap();
                if (importMap) {
                    // 有 Import Map → ESM 模式（脚本使用 import/export 语法和裸模块别名）
                    buildMode = 'esm';
                    console.log('[PlayCanvasAdapter] PlayCraft 项目检测到 Import Map，使用 ESM 模式');
                }
                else {
                    // 没有 Import Map → 回退到文件检测
                    const isESM = await this.detectESMFormat();
                    buildMode = isESM ? 'esm' : 'classic';
                }
            }
            console.log(`[PlayCanvasAdapter] 构建模式: ${buildMode}`);
        }
        catch (error) {
            console.log('[PlayCanvasAdapter] 无法加载项目配置，使用传统模式:', error.message);
        }
        const shouldEmptyOutDir = this.options.clean === true;
        const viteConfig = buildMode === 'esm'
            ? this.createESMConfig(importMap, shouldEmptyOutDir)
            : this.createClassicConfig(importMap, shouldEmptyOutDir);
        await viteBuild(viteConfig);
        const files = await this.scanOutputFiles();
        const metadata = {
            mode: buildMode,
            engine: 'playcanvas',
            buildTool: 'playcanvas-native',
            importMap: importMap ? {
                id: importMap.id,
                imports: importMap.content.imports,
            } : undefined,
            entryPoint: buildMode === 'esm' ? 'js/index.mjs' : undefined,
        };
        return {
            outputDir: this.options.outputDir,
            metadata,
            files,
        };
    }
    /**
     * 创建 ESM 模式的 Vite 配置
     */
    createESMConfig(importMap, emptyOutDir) {
        return {
            root: this.projectDir,
            base: './',
            build: {
                outDir: this.options.outputDir,
                emptyOutDir,
                write: this.options.analyze ? true : false,
                rollupOptions: {
                    input: {
                        'esm-entry': 'virtual:esm-entry',
                    },
                },
            },
            plugins: [
                {
                    name: 'virtual-esm-entry',
                    resolveId(id) {
                        if (id === 'virtual:esm-entry') {
                            return '\0virtual:esm-entry';
                        }
                        return null;
                    },
                    load(id) {
                        if (id === '\0virtual:esm-entry') {
                            return '// ESM mode - no bundling needed';
                        }
                        return null;
                    },
                },
                viteSourceBuilderPlugin({
                    projectDir: this.projectDir,
                    outputDir: this.options.outputDir,
                    selectedScenes: this.options.selectedScenes,
                    buildMode: 'esm',
                    importMap,
                }),
                ...(this.options.analyze ? [
                    visualizer({
                        filename: this.options.analyzeReportPath
                            ? path.join(this.options.outputDir, this.options.analyzeReportPath)
                            : path.join(this.options.outputDir, 'base-bundle-report.html'),
                        template: 'treemap',
                        gzipSize: true,
                        brotliSize: true,
                        open: false,
                        sourcemap: false,
                    }),
                ] : []),
            ],
        };
    }
    /**
     * 创建 Classic 模式的 Vite 配置
     */
    createClassicConfig(importMap, emptyOutDir) {
        return {
            root: this.projectDir,
            base: './',
            build: {
                outDir: this.options.outputDir,
                emptyOutDir,
                assetsInlineLimit: 0,
                minify: false,
                cssMinify: false,
                sourcemap: false,
                rollupOptions: {
                    input: {
                        'game-scripts': 'virtual:game-scripts',
                    },
                    output: {
                        entryFileNames: '__[name].js',
                        chunkFileNames: '__[name]-[hash].js',
                        assetFileNames: 'files/assets/[name].[ext]',
                        format: 'iife',
                        globals: {
                            'playcanvas': 'pc',
                            'pc': 'pc',
                        },
                    },
                    external: ['pc', 'playcanvas'],
                    treeshake: true,
                },
            },
            plugins: [
                viteSourceBuilderPlugin({
                    projectDir: this.projectDir,
                    outputDir: this.options.outputDir,
                    selectedScenes: this.options.selectedScenes,
                    buildMode: 'classic',
                    importMap,
                }),
                ...(this.options.analyze ? [
                    visualizer({
                        filename: this.options.analyzeReportPath
                            ? path.join(this.options.outputDir, this.options.analyzeReportPath)
                            : path.join(this.options.outputDir, 'base-bundle-report.html'),
                        template: 'treemap',
                        gzipSize: true,
                        brotliSize: true,
                        open: false,
                    }),
                ] : []),
            ],
        };
    }
    /**
     * 扫描输出文件
     */
    async scanOutputFiles() {
        const files = {
            html: path.join(this.options.outputDir, 'index.html'),
            engine: null,
            config: path.join(this.options.outputDir, 'config.json'),
            settings: path.join(this.options.outputDir, '__settings__.js'),
            modules: null,
            start: path.join(this.options.outputDir, '__start__.js'),
            scenes: [],
            assets: [],
        };
        // 检查 engine
        const enginePath = path.join(this.options.outputDir, 'playcanvas-stable.min.js');
        try {
            await fs.access(enginePath);
            files.engine = enginePath;
        }
        catch {
            // engine 可能不存在
        }
        // 检查 modules
        const modulesPath = path.join(this.options.outputDir, '__modules__.js');
        try {
            await fs.access(modulesPath);
            files.modules = modulesPath;
        }
        catch {
            // modules 可能不存在
        }
        // 读取 config.json 获取场景信息
        try {
            const configContent = await fs.readFile(files.config, 'utf-8');
            const configJson = JSON.parse(configContent);
            if (configJson.scenes && Array.isArray(configJson.scenes)) {
                for (const scene of configJson.scenes) {
                    if (scene.url && !scene.url.startsWith('data:')) {
                        const scenePath = path.join(this.options.outputDir, scene.url);
                        try {
                            await fs.access(scenePath);
                            files.scenes.push(scenePath);
                        }
                        catch {
                            // 场景文件可能不存在
                        }
                    }
                }
            }
            // 扫描资产文件
            const filesDir = path.join(this.options.outputDir, 'files');
            try {
                const stat = await fs.stat(filesDir);
                if (stat.isDirectory()) {
                    await this.scanDirectory(filesDir, files.assets);
                }
            }
            catch {
                // files/ 目录可能不存在
            }
        }
        catch (error) {
            console.warn('[PlayCanvasAdapter] 警告: 无法读取 config.json:', error);
        }
        return files;
    }
    /**
     * 递归扫描目录
     */
    async scanDirectory(dir, files) {
        const entries = await fs.readdir(dir, { withFileTypes: true });
        for (const entry of entries) {
            const fullPath = path.join(dir, entry.name);
            if (entry.isDirectory()) {
                await this.scanDirectory(fullPath, files);
            }
            else {
                files.push(fullPath);
            }
        }
    }
    /**
     * 记录构建产物信息
     */
    async recordBuildOutput(result) {
        console.log('[PlayCanvasAdapter] 记录构建产物信息...');
        try {
            if (result.files.html) {
                const stat = await fs.stat(result.files.html);
                this.stateManager.recordAsset('index.html', 'index.html', result.files.html, stat.size, 'html');
                this.stateManager.updateAsset('index.html', 'base-build', 'index.html', 'index.html', stat.size);
            }
            if (result.files.engine) {
                const stat = await fs.stat(result.files.engine);
                const engineName = path.basename(result.files.engine);
                this.stateManager.recordAsset('playcanvas-engine', engineName, result.files.engine, stat.size, 'script');
                this.stateManager.updateAsset('playcanvas-engine', 'base-build', engineName, engineName, stat.size);
            }
            if (result.files.config) {
                const stat = await fs.stat(result.files.config);
                this.stateManager.recordAsset('config.json', 'config.json', result.files.config, stat.size, 'json');
                this.stateManager.updateAsset('config.json', 'base-build', 'config.json', 'config.json', stat.size);
            }
            const scriptFiles = [
                { path: result.files.start, id: '__start__.js' },
                { path: result.files.settings, id: '__settings__.js' },
                { path: result.files.modules, id: '__modules__.js' },
            ];
            for (const { path: filePath, id } of scriptFiles) {
                if (filePath) {
                    try {
                        const stat = await fs.stat(filePath);
                        const fileName = path.basename(filePath);
                        this.stateManager.recordAsset(id, fileName, filePath, stat.size, 'script');
                        this.stateManager.updateAsset(id, 'base-build', fileName, fileName, stat.size);
                    }
                    catch {
                        // 文件可能不存在
                    }
                }
            }
            for (const scenePath of result.files.scenes) {
                try {
                    const stat = await fs.stat(scenePath);
                    const sceneName = path.basename(scenePath);
                    const sceneId = `scene-${sceneName}`;
                    this.stateManager.recordAsset(sceneId, sceneName, scenePath, stat.size, 'json');
                    this.stateManager.updateAsset(sceneId, 'base-build', sceneName, path.relative(this.options.outputDir, scenePath), stat.size);
                }
                catch {
                    // 忽略错误
                }
            }
            for (const assetPath of result.files.assets) {
                try {
                    const stat = await fs.stat(assetPath);
                    const assetName = path.basename(assetPath);
                    const assetId = `asset-${assetName}`;
                    const ext = path.extname(assetName).toLowerCase();
                    let assetType = 'other';
                    if (['.png', '.jpg', '.jpeg', '.webp', '.gif'].includes(ext)) {
                        assetType = 'texture';
                    }
                    else if (['.mp3', '.wav', '.ogg'].includes(ext)) {
                        assetType = 'audio';
                    }
                    else if (['.glb', '.gltf', '.obj', '.fbx'].includes(ext)) {
                        assetType = 'model';
                    }
                    this.stateManager.recordAsset(assetId, assetName, assetPath, stat.size, assetType);
                    this.stateManager.updateAsset(assetId, 'base-build', assetName, path.relative(this.options.outputDir, assetPath), stat.size);
                }
                catch {
                    // 忽略错误
                }
            }
            console.log('[PlayCanvasAdapter] 构建产物信息已记录');
        }
        catch (error) {
            console.error('[PlayCanvasAdapter] 记录构建产物信息失败:', error);
        }
    }
    /**
     * 生成构建分析报告
     */
    async generateAnalysisReport() {
        console.log('\n[PlayCanvasAdapter] 生成构建分析报告...');
        try {
            const analyzer = new BuildAnalyzer(this.options.outputDir, this.options.outputDir);
            const report = await analyzer.analyze();
            const reportPath = await analyzer.generateHTMLReport(report);
            // 删除旧的报告
            const oldReportPath = path.join(this.options.outputDir, 'base-bundle-report.html');
            try {
                await fs.unlink(oldReportPath);
            }
            catch {
                // 文件可能不存在，忽略
            }
            console.log(`\n📊 构建分析报告:`);
            console.log(`   文件总数: ${report.totalFiles}`);
            console.log(`   当前总大小: ${report.totalSizeFormatted}`);
            console.log(`   预估单 HTML 大小: ${report.estimatedHtmlSizeFormatted}`);
            console.log(`   报告路径: ${reportPath}\n`);
        }
        catch (error) {
            console.error('[PlayCanvasAdapter] 生成分析报告失败:', error);
        }
    }
}
