const fs = require("fs");
const path = require("path");
const { spawn, spawnSync } = require("child_process");

const mode = process.argv[2] === "prod" ? "prod" : "local";
const defaultApiBase = mode === "prod" ? "https://dlxlh.dtacloud.cn" : "http://localhost:8082";
const apiBase = String(process.env.TARO_APP_API_BASE || defaultApiBase).replace(/\/+$/, "");
const env = {
  ...process.env,
  TARO_APP_API_BASE: apiBase,
  TARO_APP_UPLOAD_BASE: process.env.TARO_APP_UPLOAD_BASE || apiBase,
  SKILL_CONFIG_OPTIONAL: "1",
};

const npx = process.platform === "win32" ? "npx.cmd" : "npx";
const skillConfigFile = path.resolve(__dirname, "..", "dist", "skills", "activity-skill", "utils", "config.js");

function syncSkillConfig() {
  if (!fs.existsSync(path.dirname(skillConfigFile))) return;
  spawnSync(process.execPath, ["scripts/write-skill-config.js", mode], {
    stdio: "inherit",
    env,
  });
}

const watcher = spawn(npx, ["taro", "build", "--type", "weapp", "--watch"], {
  stdio: "inherit",
  env,
});

const interval = setInterval(syncSkillConfig, 3000);
syncSkillConfig();

function stop(signal) {
  clearInterval(interval);
  if (!watcher.killed) watcher.kill(signal);
}

watcher.on("exit", (code, signal) => {
  clearInterval(interval);
  if (signal) process.kill(process.pid, signal);
  process.exit(code || 0);
});

process.on("SIGINT", () => stop("SIGINT"));
process.on("SIGTERM", () => stop("SIGTERM"));
