const fs = require('fs');
const path = require('path');

const floorDir = __dirname;
const files = fs.readdirSync(floorDir).filter(f => f.match(/^MT\d+[a-z]?\.js$|^MT_\d\.js$/i)).sort();

const allMaps = {};

files.forEach(file => {
    const filePath = path.join(floorDir, file);
    const content = fs.readFileSync(filePath, 'utf8');
    
    // 提取 floorId
    const floorIdMatch = content.match(/"floorId":\s*"([^"]+)"/);
    
    if (floorIdMatch) {
        const floorId = floorIdMatch[1];
        
        // 使用更精确的正则表达式提取map数组
        // 先找到 "map": [ 的位置，然后匹配到相应的 ],
        const mapStartIndex = content.indexOf('"map": [');
        if (mapStartIndex === -1) {
            console.log(`✗ 未找到map: ${file}`);
            return;
        }
        
        // 计数括号，找到匹配的闭合括号
        let bracketCount = 0;
        let inString = false;
        let escapeNext = false;
        let mapEndIndex = -1;
        
        for (let i = mapStartIndex + 8; i < content.length; i++) {
            const char = content[i];
            
            if (escapeNext) {
                escapeNext = false;
                continue;
            }
            
            if (char === '\\') {
                escapeNext = true;
                continue;
            }
            
            if (char === '"') {
                inString = !inString;
                continue;
            }
            
            if (!inString) {
                if (char === '[') {
                    bracketCount++;
                } else if (char === ']') {
                    if (bracketCount === 0) {
                        mapEndIndex = i;
                        break;
                    }
                    bracketCount--;
                }
            }
        }
        
        if (mapEndIndex !== -1) {
            try {
                const mapStr = content.substring(mapStartIndex + 7, mapEndIndex + 1);
                const mapArray = JSON.parse(mapStr);
                allMaps[floorId] = {
                    file: file,
                    map: mapArray
                };
                console.log(`✓ 已提取: ${file} (floorId: ${floorId})`);
            } catch (e) {
                console.log(`✗ 提取失败: ${file} - ${e.message}`);
            }
        } else {
            console.log(`✗ 找不到map闭合括号: ${file}`);
        }
    }
});

// 保存为JSON文件
const outputPath = path.join(floorDir, 'all_maps.json');
fs.writeFileSync(outputPath, JSON.stringify(allMaps, null, 2), 'utf8');
console.log(`\n✓ 完成！文件已保存到: all_maps.json`);
console.log(`✓ 总共提取了 ${Object.keys(allMaps).length} 层的map数据`);
