#!/usr/bin/env node

const fs = require("node:fs");
const path = require("node:path");
const process = require("node:process");
const ci = require("miniprogram-ci");

function requireEnvironment(name) {
  const value = process.env[name];
  if (!value) {
    throw new Error(`${name} is required.`);
  }
  return value;
}

async function main() {
  const projectPath = process.cwd();
  const privateKeyPath = path.resolve(
    requireEnvironment("WECHAT_CI_PRIVATE_KEY_PATH"),
  );
  const qrcodeOutputDest = path.resolve(
    requireEnvironment("MINIAPP_QR_OUTPUT"),
  );
  const appid = requireEnvironment("MINIAPP_APPID");
  const robot = Number.parseInt(process.env.MINIAPP_ROBOT ?? "1", 10);
  const versionLabel = requireEnvironment("MINIAPP_VERSION_LABEL");

  if (!fs.existsSync(path.join(projectPath, "project.config.json"))) {
    throw new Error("The working directory must contain project.config.json.");
  }
  if (!fs.existsSync(privateKeyPath)) {
    throw new Error("The WeChat code-upload key file does not exist.");
  }
  if (!Number.isInteger(robot) || robot < 1 || robot > 30) {
    throw new Error("MINIAPP_ROBOT must be an integer from 1 to 30.");
  }

  const project = new ci.Project({
    appid,
    type: "miniProgram",
    projectPath,
    privateKeyPath,
    ignores: ["node_modules/**/*", ".git/**/*"],
  });

  await ci.preview({
    project,
    desc: `Automated preview ${versionLabel}`.slice(0, 50),
    robot,
    setting: {
      useProjectConfig: true,
      es6: true,
      es7: true,
      enhance: true,
      minify: true,
      autoPrefixWXSS: true,
    },
    qrcodeFormat: "image",
    qrcodeOutputDest,
    onProgressUpdate: (progress) => {
      if (typeof progress === "string") {
        console.log(progress);
      }
    },
  });

  console.log(`Preview QR code created: ${qrcodeOutputDest}`);
}

main().catch((error) => {
  console.error(`Mini Program preview failed: ${error.message}`);
  process.exitCode = 1;
});
