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

// 读取HTML文件
const htmlFilePath = path.join(__dirname, 'src/app/pages/designer/project-detail/project-detail.html');
let htmlContent = fs.readFileSync(htmlFilePath, 'utf8');

console.log('开始修复HTML结构...');

// 分析并修复HTML结构
function fixHtmlStructure(content) {
    const lines = content.split('\n');
    const stack = [];
    const fixedLines = [];
    let inIfBlock = false;
    let ifBlockDepth = 0;
    
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        const trimmedLine = line.trim();
        
        // 检测@if控制流
        if (trimmedLine.includes('@if')) {
            inIfBlock = true;
            ifBlockDepth++;
            fixedLines.push(line);
            continue;
        }
        
        // 检测@if控制流结束
        if (inIfBlock && trimmedLine === '}') {
            ifBlockDepth--;
            if (ifBlockDepth === 0) {
                inIfBlock = false;
            }
            fixedLines.push(line);
            continue;
        }
        
        // 检测div开始标签
        if (trimmedLine.includes('<div')) {
            const divMatch = trimmedLine.match(/<div[^>]*>/);
            if (divMatch && !trimmedLine.includes('</div>')) {
                stack.push({
                    tag: 'div',
                    line: i + 1,
                    content: divMatch[0]
                });
            }
            fixedLines.push(line);
            continue;
        }
        
        // 检测div结束标签
        if (trimmedLine.includes('</div>')) {
            if (stack.length > 0 && stack[stack.length - 1].tag === 'div') {
                stack.pop();
            } else {
                console.log(`警告：第${i + 1}行发现多余的</div>标签，已移除`);
                continue; // 跳过多余的结束标签
            }
        }
        
        fixedLines.push(line);
    }
    
    // 添加缺失的结束标签
    while (stack.length > 0) {
        const unclosed = stack.pop();
        if (unclosed.tag === 'div') {
            fixedLines.push('</div>');
            console.log(`添加缺失的</div>标签`);
        }
    }
    
    return fixedLines.join('\n');
}

// 修复HTML结构
const fixedContent = fixHtmlStructure(htmlContent);

// 写回文件
fs.writeFileSync(htmlFilePath, fixedContent, 'utf8');

console.log('HTML结构修复完成！');