"use strict";
// Windows 開機自動啟動：HKCU\Software\Microsoft\Windows\CurrentVersion\Run\ClaudePet
const path = require("node:path");
const fs = require("node:fs");
const { spawnSync } = require("node:child_process");
const { isPackaged, portableExe } = require("./paths");

const APP_DIR = path.resolve(__dirname, "..");
const RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
const VALUE_NAME = "ClaudePet";

function electronExe() {
  return path.join(APP_DIR, "node_modules", "electron", "dist", "electron.exe");
}

function command() {
  // 打包後就是那顆 exe 本身。portable 版的 process.execPath 會指到 %TEMP% 的解壓副本，
  // 要用 PORTABLE_EXECUTABLE_FILE 才是使用者手上那顆 exe。
  if (isPackaged()) return `"${portableExe() || process.execPath}"`;
  return `"${electronExe()}" "${APP_DIR}"`;
}

function reg(args) {
  const r = spawnSync("reg", args, { encoding: "utf8", windowsHide: true });
  return { ok: r.status === 0, stdout: r.stdout || "", stderr: r.stderr || "" };
}

function isInstalled() {
  if (process.platform !== "win32") return false;
  return reg(["query", RUN_KEY, "/v", VALUE_NAME]).ok;
}

function currentValue() {
  const r = reg(["query", RUN_KEY, "/v", VALUE_NAME]);
  if (!r.ok) return null;
  const m = r.stdout.match(/REG_SZ\s+(.+)$/m);
  return m ? m[1].trim() : null;
}

function install() {
  if (process.platform !== "win32") throw new Error("只支援 Windows");
  if (!isPackaged() && !fs.existsSync(electronExe())) throw new Error(`找不到 Electron：${electronExe()}（先執行 npm install）`);
  const r = reg(["add", RUN_KEY, "/v", VALUE_NAME, "/t", "REG_SZ", "/d", command(), "/f"]);
  if (!r.ok) throw new Error(r.stderr || r.stdout || "reg add 失敗");
  return command();
}

function uninstall() {
  if (process.platform !== "win32") return false;
  const r = reg(["delete", RUN_KEY, "/v", VALUE_NAME, "/f"]);
  return r.ok;
}

module.exports = { install, uninstall, isInstalled, currentValue, command, electronExe, VALUE_NAME, RUN_KEY };
