import fs from "fs";
import path from "path";

 

export function updateVersion() {
  // 读取 package.json 版本
  const packageJson = JSON.parse(fs.readFileSync("./package.json", "utf8"));
  const version = packageJson.version;

  const rootDir = process.cwd();

  // 更新 Android 版本
  const androidBuildGradlePath = path.join(rootDir, "android/app/build.gradle");
  if (fs.existsSync(androidBuildGradlePath)) {
    let androidBuildGradle = fs.readFileSync(androidBuildGradlePath, "utf8");
    androidBuildGradle = androidBuildGradle.replace(
      /versionName\s+".*?"/,
      `versionName "${version}"`
    );
    fs.writeFileSync(androidBuildGradlePath, androidBuildGradle);
  } else {
    console.log("没有找到 Android build.gradle 文件。");
  }

  // 更新 iOS 版本
  const iosPlistPath = path.join(rootDir, "ios/App/App/Info.plist");
  if (fs.existsSync(iosPlistPath)) {
    let iosPlist = fs.readFileSync(iosPlistPath, "utf8");
    iosPlist = iosPlist.replace(
      /<key>CFBundleShortVersionString<\/key>\s*<string>.*?<\/string>/,
      `<key>CFBundleShortVersionString</key>\n\t<string>${version}</string>`
    );
    fs.writeFileSync(iosPlistPath, iosPlist);
  } else {
    console.log("没有找到iOS plist文件");
  }

  console.log(`✅ 版本号已同步至: ${version}`);
  return version;
};
  