const { spawnSync } = require("child_process");

const mode = process.argv[2] === "prod" ? "prod" : "local";
const apiBase = mode === "prod" ? "https://dlxlh.dtacloud.cn" : "http://localhost:8082";
const env = {
  ...process.env,
  NODE_ENV: mode === "prod" ? "production" : "development",
  TARO_APP_API_BASE: apiBase,
  TARO_APP_UPLOAD_BASE: apiBase,
};

const cleanOutput = spawnSync(process.execPath, ["scripts/clean-output-dir.js", "dist"], {
  stdio: "inherit",
  env,
});

if (cleanOutput.status !== 0) {
  process.exit(cleanOutput.status || 1);
}

const npx = process.platform === "win32" ? "npx.cmd" : "npx";
const build = spawnSync(npx, ["taro", "build", "--type", "weapp", "--env", mode === "prod" ? "production" : "development"], {
  stdio: "inherit",
  env,
});

if (build.status !== 0) {
  process.exit(build.status || 1);
}

const writeSkillConfig = spawnSync(process.execPath, ["scripts/write-skill-config.js", mode], {
  stdio: "inherit",
  env,
});

if (writeSkillConfig.status !== 0) {
  process.exit(writeSkillConfig.status || 1);
}

const cleanAppleDouble = spawnSync(process.execPath, ["scripts/clean-appledouble.js", "dist"], {
  stdio: "inherit",
  env,
});

if (cleanAppleDouble.status !== 0) {
  process.exit(cleanAppleDouble.status || 1);
}

const verify = spawnSync(process.execPath, ["scripts/verify-weapp-env.js", mode], {
  stdio: "inherit",
  env,
});

if (verify.status !== 0) {
  process.exit(verify.status || 1);
}

const finalCleanAppleDouble = spawnSync(process.execPath, ["scripts/clean-appledouble.js", "dist"], {
  stdio: "inherit",
  env,
});

process.exit(finalCleanAppleDouble.status || 0);
