#!/usr/bin/env node
"use strict";

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

const root = path.resolve(__dirname, "..");

function fail(msg) {
  console.error(`\x1b[31m[ivox] ✗ ${msg}\x1b[0m`);
  process.exit(1);
}

function warn(msg) {
  console.warn(`\x1b[33m[ivox] ! ${msg}\x1b[0m`);
}

function info(msg) {
  console.log(`[ivox] ${msg}`);
}

function copyBinary(src, dst) {
  fs.mkdirSync(path.dirname(dst), { recursive: true });
  fs.copyFileSync(src, dst);
  fs.chmodSync(dst, 0o755);
}

function main() {
  if (process.platform !== "darwin") {
    fail("iVox only supports macOS (Apple Silicon).");
  }

  const arch = process.arch === "arm64" ? "arm64" : "x64";
  info(`macOS ${arch}`);

  const binDir = path.join(os.homedir(), ".local", "bin");
  const dstPath = path.join(binDir, "ivoxd");
  const prebuiltName = `ivoxd-darwin-${arch}`;
  const prebuiltPath = path.join(root, "npm", "bin", prebuiltName);

  // 1. 优先用预编译二进制
  const pkg = require(path.join(root, "package.json"));

  if (fs.existsSync(prebuiltPath)) {
    info(`使用预编译二进制: ${prebuiltName}`);
    copyBinary(prebuiltPath, dstPath);
    console.log(`\n✅ iVox v${pkg.version} 已安装`);
    console.log("首次使用运行: ivox setup");
    return;
  }

  // 2. Fallback: Go 源码编译
  warn("未找到预编译二进制，尝试源码编译...");

  const goCheck = spawnSync("go", ["version"], { stdio: "ignore" });
  if (goCheck.status !== 0) {
    fail("需要 Go 编译器。请安装 Go 后重试，或联系维护者获取预编译包。");
  }
  const buildPath = path.join(root, "build", "ivoxd");
  fs.mkdirSync(path.dirname(buildPath), { recursive: true });

  info("编译 ivoxd...");
  const build = spawnSync("go", ["build",
    "-ldflags", `-s -w -X main.version=${pkg.version}`,
    "-o", buildPath, "."], {
    cwd: root,
    stdio: "inherit",
  });
  if (build.status !== 0) {
    fail("编译失败，请检查 Go 环境。");
  }

  copyBinary(buildPath, dstPath);
  console.log(`\n✅ iVox v${pkg.version} 已安装 (源码编译)`);
  console.log("首次使用运行: ivox setup");
}

main();
