// post-build-process.js
const fs = require('fs');
const path = require('path');

function processHtml() {
    const distHtmlPath = path.join(__dirname, 'dist', 'index.html');

    console.log('开始处理打包后的 HTML 文件...');
    console.log('文件路径:', distHtmlPath);

    if (!fs.existsSync(distHtmlPath)) {
        console.log('❌ 文件不存在:', distHtmlPath);
        return;
    }

    let htmlContent = fs.readFileSync(distHtmlPath, 'utf-8');
    console.log('文件大小:', htmlContent.length, '字符');

    // 查找所有包含目标代码的行
    const lines = htmlContent.split('\n');
    let found = false;

    for (let i = 0; i < lines.length; i++) {
        if (lines[i].includes('try{import("_").catch(()=>1);')) {
            console.log(`在第 ${i + 1} 行找到目标代码:`);
            console.log('原内容:', lines[i].trim());

            lines[i] = lines[i].replace(
                'try{import("_").catch(()=>1);}catch(e){}window.__vite_is_dynamic_import_support=true;',
                'try{import("_").catch(()=>return);}catch(e){}window.__vite_is_dynamic_import_support=true;'
            );

            console.log('新内容:', lines[i].trim());
            found = true;
            break;
        }
    }

    if (found) {
        const newContent = lines.join('\n');
        fs.writeFileSync(distHtmlPath, newContent, 'utf-8');
        console.log('✓ 成功修改 HTML 文件');
    } else {
        console.log('❌ 未找到目标代码');
        // 输出所有包含相关关键词的行
        console.log('搜索相关行...');
        lines.forEach((line, index) => {
            if (line.includes('import("_")') || line.includes('__vite_is_dynamic_import_support') || line.includes('catch(()=>1)')) {
                console.log(`第${index + 1}行:`, line.trim());
            }
        });
    }
}

processHtml();