import fs from 'fs/promises';
import path from 'path';
/**
 * 构建状态版本
 */
export const BUILD_STATE_VERSION = '1.0.0';
/**
 * 构建状态管理器
 * 负责记录和管理构建过程中的资源处理信息
 */
export class BuildStateManager {
    constructor(projectDir, outputDir) {
        this.outputDir = outputDir;
        this.stateFilePath = path.join(outputDir, 'build-state.json');
        // 初始化状态
        this.state = {
            version: BUILD_STATE_VERSION,
            projectDir,
            stages: [],
            assets: {},
            createdAt: Date.now(),
            updatedAt: Date.now(),
        };
    }
    /**
     * 静态方法：从输出目录加载 build-state.json，返回管理器或 null
     */
    static async load(outputDir) {
        const manager = new BuildStateManager(outputDir, outputDir);
        const ok = await manager.loadState();
        return ok ? manager : null;
    }
    /**
     * 从文件加载状态
     */
    async loadState() {
        try {
            const content = await fs.readFile(this.stateFilePath, 'utf-8');
            const loadedState = JSON.parse(content);
            // 验证版本
            if (loadedState.version !== BUILD_STATE_VERSION) {
                console.warn(`[BuildStateManager] 状态文件版本不匹配: ${loadedState.version} vs ${BUILD_STATE_VERSION}`);
                return false;
            }
            this.state = loadedState;
            console.log(`[BuildStateManager] 已加载状态文件: ${Object.keys(this.state.assets).length} 个资源`);
            return true;
        }
        catch (error) {
            // 文件不存在或解析失败
            return false;
        }
    }
    /**
     * 保存状态到文件
     */
    async saveState() {
        this.state.updatedAt = Date.now();
        // 确保输出目录存在
        await fs.mkdir(this.outputDir, { recursive: true });
        // 保存状态文件
        await fs.writeFile(this.stateFilePath, JSON.stringify(this.state, null, 2), 'utf-8');
        console.log(`[BuildStateManager] 状态已保存: ${this.stateFilePath}`);
    }
    /**
     * 开始构建阶段
     */
    startStage(stage, options = {}) {
        this.state.stages.push({
            stage,
            startTime: Date.now(),
            outputDir: this.outputDir,
            options,
        });
        console.log(`[BuildStateManager] 开始阶段: ${stage}`);
    }
    /**
     * 结束构建阶段
     */
    endStage() {
        const currentStage = this.state.stages[this.state.stages.length - 1];
        if (currentStage) {
            currentStage.endTime = Date.now();
            const duration = currentStage.endTime - currentStage.startTime;
            console.log(`[BuildStateManager] 结束阶段: ${currentStage.stage} (耗时 ${duration}ms)`);
        }
    }
    /**
     * 记录资源
     */
    recordAsset(id, originalName, originalPath, originalSize, type, metadata) {
        if (!this.state.assets[id]) {
            this.state.assets[id] = {
                id,
                originalName,
                originalPath,
                originalSize,
                type,
                processingHistory: [],
                finalSize: originalSize,
                totalCompressionRatio: 0,
                metadata,
            };
            console.log(`[BuildStateManager] 记录资源: ${originalName} (${type}, ${originalSize} bytes)`);
        }
    }
    /**
     * 更新资源处理信息
     */
    updateAsset(id, stage, name, assetPath, size, options = {}) {
        const asset = this.state.assets[id];
        if (!asset) {
            console.warn(`[BuildStateManager] 资源不存在: ${id}`);
            return;
        }
        // 计算压缩率
        const previousSize = asset.processingHistory.length > 0
            ? asset.processingHistory[asset.processingHistory.length - 1].size
            : asset.originalSize;
        const compressionRatio = previousSize > 0
            ? 1 - (size / previousSize)
            : 0;
        // 添加处理信息
        const processingInfo = {
            stage,
            name,
            path: assetPath,
            size,
            optimizations: options.optimizations || [],
            compressionRatio: compressionRatio > 0 ? compressionRatio : undefined,
            inlined: options.inlined || false,
            inlineLocation: options.inlineLocation,
            timestamp: Date.now(),
        };
        asset.processingHistory.push(processingInfo);
        asset.finalSize = size;
        // 计算总压缩率
        asset.totalCompressionRatio = asset.originalSize > 0
            ? 1 - (size / asset.originalSize)
            : 0;
        // 更新元数据
        if (options.metadata) {
            asset.metadata = { ...asset.metadata, ...options.metadata };
        }
        console.log(`[BuildStateManager] 更新资源: ${name} (${stage}, ${size} bytes, 压缩率 ${(compressionRatio * 100).toFixed(1)}%)`);
    }
    /**
     * 获取资源状态
     */
    getAsset(id) {
        return this.state.assets[id];
    }
    /**
     * 获取所有资源
     */
    getAllAssets() {
        return Object.values(this.state.assets);
    }
    /**
     * 获取按类型分组的资源
     */
    getAssetsByType() {
        const result = {};
        for (const asset of Object.values(this.state.assets)) {
            if (!result[asset.type]) {
                result[asset.type] = [];
            }
            result[asset.type].push(asset);
        }
        return result;
    }
    /**
     * 获取构建状态
     */
    getState() {
        return this.state;
    }
    /**
     * 获取统计信息
     */
    getStatistics() {
        const assets = Object.values(this.state.assets);
        const totalOriginalSize = assets.reduce((sum, asset) => sum + asset.originalSize, 0);
        const totalFinalSize = assets.reduce((sum, asset) => sum + asset.finalSize, 0);
        const totalCompressionRatio = totalOriginalSize > 0
            ? 1 - (totalFinalSize / totalOriginalSize)
            : 0;
        const byType = {};
        for (const asset of assets) {
            if (!byType[asset.type]) {
                byType[asset.type] = { count: 0, originalSize: 0, finalSize: 0 };
            }
            byType[asset.type].count++;
            byType[asset.type].originalSize += asset.originalSize;
            byType[asset.type].finalSize += asset.finalSize;
        }
        return {
            totalAssets: assets.length,
            totalOriginalSize,
            totalFinalSize,
            totalCompressionRatio,
            byType,
        };
    }
    /**
     * 验证状态数据的完整性
     */
    validate() {
        const errors = [];
        // 检查版本
        if (this.state.version !== BUILD_STATE_VERSION) {
            errors.push(`版本不匹配: ${this.state.version} vs ${BUILD_STATE_VERSION}`);
        }
        // 检查必需字段
        if (!this.state.projectDir) {
            errors.push('缺少 projectDir');
        }
        // 检查资源数据
        for (const [id, asset] of Object.entries(this.state.assets)) {
            if (asset.id !== id) {
                errors.push(`资源 ID 不匹配: ${id} vs ${asset.id}`);
            }
            if (!asset.originalName) {
                errors.push(`资源 ${id} 缺少 originalName`);
            }
            if (asset.originalSize < 0) {
                errors.push(`资源 ${id} 的 originalSize 无效: ${asset.originalSize}`);
            }
        }
        return {
            valid: errors.length === 0,
            errors,
        };
    }
}
