import { appTasks } from '@ohos/hvigor-ohos-plugin';
import fs from 'fs';
import path from 'path';

/*
function updateJsonTime() {
  const filePath = path.resolve(__dirname, 'build-profile.json5');
  if (fs.existsSync(filePath)) {
    const now = new Date();
    const timeStr = `${now.getFullYear()}${now.getMonth() + 1}${now.getDate()}${now.getHours()}${now.getMinutes()}`;
    const newArtifactName = `rabbit_harmony_${timeStr}_`;

    let content = fs.readFileSync(filePath, 'utf8');
    // 使用正则表达式精准匹配 BUILD_TIME 后的值并替换，匹配模式： "BUILD_TIME": "任意内容"
    const updateTimeContent = content.replace(/("BUILD_TIME"\s*:\s*")[^"]*(")/g, `$1${timeStr}$2`);
    const newContent = updateTimeContent.replace(/("artifactName"\s*:\s*")[^"]*(")/g, `$1${newArtifactName}$2`);

    if (content !== newContent) {
      fs.writeFileSync(filePath, newContent, 'utf8');
    }
  }
}
updateJsonTime();
*/

function syncBuildFileNameByJson() {
  const filePath = path.resolve(__dirname, 'build-profile.json5');
  if (!fs.existsSync(filePath)) return;

  try {
    // 1. 读取并解析 JSON (JSON5 格式通常可以当作普通字符串解析)
    const rawContent = fs.readFileSync(filePath, 'utf8');

    // 使用正则提取关键信息，避免因 JSON5 语法导致的 JSON.parse 失败
    const signingMatch = rawContent.match(/"signingConfig"\s*:\s*"([^"]+)"/);
    const signingConfig = signingMatch ? signingMatch[1] : 'debug';

    let buildMode = 'debug';
    const profile = JSON.parse(rawContent);

    // 查找对于签名下的 buildModeSet 中 name 为 debug 的 debuggable 值，正则逻辑：定位到 name: "debug" 块，寻找其后的 debuggable 状态
    if (signingConfig === 'debug') {
      const releaseConfig = profile.app.buildModeSet.find(item => item.name === 'debug');
      const isDebuggable = releaseConfig ? releaseConfig.buildOption.debuggable : true;
      buildMode = isDebuggable ? 'debug' : 'release';
    } else if (signingConfig === 'release') {
      const releaseConfig = profile.app.buildModeSet.find(item => item.name === 'release');
      const isDebuggable = releaseConfig ? releaseConfig.buildOption.debuggable : true;
      buildMode = isDebuggable ? 'debug' : 'release';
    }

    // 2. 生成动态名称
    const now = new Date();
    const timeStr = `${now.getFullYear().toString().slice(-2)}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`;
    const newName = `rabbit_harmony_${buildMode}_${timeStr}`;

    // 3. 物理替换并写入
    const updatedArtifactName = rawContent.replace(/("artifactName"\s*:\s*")[^"]*(")/g, `$1${newName}$2`);

    const updateBuildTimeContent = updatedArtifactName.replace(/("BUILD_TIME"\s*:\s*")[^"]*(")/g, `$1${timeStr}$2`);
    const updatedContent = updateBuildTimeContent

    if (rawContent !== updatedContent) {
      fs.writeFileSync(filePath, updatedContent, 'utf8');
    }
  } catch (e) {
    console.error('>>>> [Error] 解析 build-profile.json5 失败: ' + e.message);
  }
}

// 脚本加载即执行
syncBuildFileNameByJson();

export default {
  system: appTasks,
  plugins: []
};