import { writeFileSync, readFileSync } from "fs";
import { execSync } from "child_process";
import moment from "moment";
import packageJson from "./package.json" assert { type: "json" };

console.log("> prebuild");
console.log(process.argv);

if (process.argv.length < 3) {
  console.log(
    "命令格式：\nnode --experimental-json-modules prebuild.mjs [mode]"
  );
  process.exit(1);
}

console.log("删除license注释，避免混淆文件被推测");
let str = readFileSync(
  "./node_modules/pinia/dist/pinia.esm-browser.js"
).toString();
console.log(
  str.slice(0, 100),
  str.replace(/\s+\* @license MIT\s*/, "").slice(0, 100)
);
writeFileSync(
  "./node_modules/pinia/dist/pinia.esm-browser.js",
  str.replace(/\s+\* @license MIT\s*/, "")
);
str = readFileSync("./node_modules/js-md5/src/md5.js").toString();
writeFileSync(
  "./node_modules/js-md5/src/md5.js",
  str.replace(/\s+\* @license MIT\s*/, "")
);
str = readFileSync(
  "./node_modules/.pnpm/sortablejs@1.14.0/node_modules/sortablejs/modular/sortable.esm.js"
).toString();
writeFileSync(
  "./node_modules/.pnpm/sortablejs@1.14.0/node_modules/sortablejs/modular/sortable.esm.js",
  str.replace(/\s+\* @license MIT\s*/, "")
);

const mode = process.argv[2];
const validModes = ["production", "staging", "test", "dev"];
if (!validModes.includes(mode)) {
  console.log(`mode: ${mode} 不合法，合法的mode为 `, validModes);
  process.exit(1);
}

const localEnv = ".env." + mode + ".local";
console.log("> prebuild create " + localEnv);

// const packageJson = require("./package.json");

const buildDate = moment().format("YYYY-MM-DD HH:mm:ss");
console.log("  构建日期为 " + buildDate);

// eslint-disable-next-line @typescript-eslint/no-unsafe-call
const revision = execSync("git rev-parse HEAD").toString().trim().slice(0, 7);
console.log("  当前的git版本为 " + revision);

// eslint-disable-next-line @typescript-eslint/no-unsafe-call
writeFileSync(
  localEnv,
  `VITE_FE_VERSION=${packageJson.version}
VITE_BUILD_DATE=${buildDate}
VITE_GIT_REPO_VERSION=${revision}
`
);

console.log();
