#!/usr/bin/env node
import path from "path";
import { spawnSync } from "child_process";
import readline from "readline";
import { fileURLToPath } from "url";

const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const langfuseCli = path.join(rootDir, "bin", "langfuse-cli.js");
const reportCli = path.join(rootDir, "opencode-ohai-report", "bin", "cli.js");
const skillhubCli = path.join(rootDir, "scripts", "skillhub-install.mjs");

function nodeMajorVersion() {
  const raw = process.versions && process.versions.node ? process.versions.node : "0.0.0";
  return Number.parseInt(raw.split(".")[0], 10) || 0;
}

function assertSupportedNode() {
  if (nodeMajorVersion() >= 16) return;
  console.error("oh-aicoding-tool requires Node.js >= 16.");
  console.error(`Current Node.js: ${process.version}`);
  console.error("Please upgrade Node.js, then run: npx oh-aicoding-tool@latest");
  process.exit(1);
}

function createPromptInterface(options) {
  const rl = readline.createInterface(options);
  return {
    question(query) {
      return new Promise((resolve) => rl.question(query, resolve));
    },
    close() {
      rl.close();
    },
  };
}

const colorEnabled = process.stdout.isTTY && process.env.NO_COLOR !== "1";
const ansi = (code) => (colorEnabled ? `\x1b[${code}m` : "");
const rgb = (r, g, b) => (colorEnabled ? `\x1b[38;2;${r};${g};${b}m` : "");
const bg = (r, g, b) => (colorEnabled ? `\x1b[48;2;${r};${g};${b}m` : "");
const t = {
  reset: ansi(0),
  bold: ansi(1),
  cyan: rgb(92, 214, 255),
  teal: rgb(92, 232, 188),
  blue: rgb(132, 167, 255),
  gold: rgb(245, 202, 116),
  red: rgb(255, 117, 117),
  muted: rgb(140, 151, 166),
  panel: rgb(75, 86, 105),
  selectedBg: bg(31, 53, 68),
  selectedFg: rgb(218, 250, 255),
};

function paint(value, ...styles) {
  if (!colorEnabled) return String(value);
  return `${styles.join("")}${value}${t.reset}`;
}

function terminalWidth() {
  return Math.max(72, Math.min(process.stdout.columns || 88, 104));
}

function clearScreen() {
  if (process.stdout.isTTY) process.stdout.write("\x1b[2J\x1b[H");
}

function prepareStdinForChildProcess() {
  if (!process.stdin.isTTY) return;
  try {
    process.stdin.setRawMode(false);
  } catch {}
  process.stdin.pause();
}

function readRawKey(chunk) {
  const value = chunk.toString("utf8");
  if (value === "\u0003") return { name: "c", ctrl: true };
  if (value === "\r" || value === "\n" || value === "\r\n") return { name: "enter" };
  if (value === " ") return { name: "space" };
  if (value === "\u001b") return { name: "escape" };
  if (value === "\u001b[A" || value === "\u001bOA" || value === "\x00H" || value === "\u00e0H") return { name: "up" };
  if (value === "\u001b[B" || value === "\u001bOB" || value === "\x00P" || value === "\u00e0P") return { name: "down" };
  if (/^[1-9]$/.test(value)) return { name: "number", number: Number.parseInt(value, 10) };
  if (/^[qQ]$/.test(value)) return { name: "q" };
  return { name: "", sequence: value };
}

function rule(width = terminalWidth()) {
  return paint("-".repeat(width), t.panel);
}

function renderHeader(subtitle = "交互式安装") {
  clearScreen();
  console.log("");
  console.log(`${paint("oh-aicoding-tool", t.bold, t.teal)} ${paint(subtitle, t.cyan)}`);
  console.log(rule());
  console.log(
    `${paint("Space", t.gold)} 选择/取消  ${paint("Enter", t.gold)} 继续  ` +
      `${paint("Up/Down", t.gold)} 移动  ${paint("q", t.gold)} 退出`
  );
}

function runNodeScript(script, args) {
  prepareStdinForChildProcess();
  const result = spawnSync(process.execPath, [script, ...args], {
    stdio: "inherit",
    windowsHide: true,
  });
  const code = result.status != null ? result.status : result.error ? 1 : 0;
  console.log("");
  if (code === 0) {
    console.log(paint("✓ 执行成功", t.bold, t.teal));
  } else {
    console.log(paint(`✕ 执行失败(退出码 ${code})`, t.bold, t.red));
  }
  return code;
}

function printHelp() {
  console.log("oh-aicoding-tool");
  console.log("");
  console.log("用法:");
  console.log("  oh-aicoding-tool                         打开交互式安装菜单");
  console.log("  oh-aicoding-tool langfuse [setup|check|verify-update] [target]");
  console.log("  oh-aicoding-tool langfuse update [all|claude|opencode|codex]");
  console.log("  oh-aicoding-tool langfuse verify-update [all|claude|opencode|codex]");
  console.log("  oh-aicoding-tool report install opencode [--email name@company.com]");
  console.log("  oh-aicoding-tool report install claude");
  console.log("  oh-aicoding-tool report install codex");
  console.log("  oh-aicoding-tool report install both");
  console.log("  oh-aicoding-tool report install all");
  console.log("  oh-aicoding-tool report doctor");
  console.log("  oh-aicoding-tool skill");
  console.log("  oh-aicoding-tool skill clean");
  console.log("");
  console.log("兼容命令:");
  console.log("  code-tool-langfuse");
  console.log("  opencode-ohai-report");
  console.log("  ohai-report");
  console.log("  oh-skillhub");
}

function emailIsValid(value) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || "").trim());
}

function renderChoiceScreen(title, choices, index, subtitle) {
  renderHeader(subtitle);
  console.log("");
  console.log(paint(title, t.bold, t.blue));
  console.log("");
  choices.forEach((choice, idx) => {
    const focused = idx === index;
    const cursor = focused ? paint(">", t.teal, t.bold) : " ";
    const label = focused
      ? paint(` ${choice.label} `, t.bold, t.selectedFg, t.selectedBg)
      : paint(choice.label, t.bold);
    console.log(` ${cursor} ${paint(`[${idx + 1}]`, focused ? t.selectedFg : t.muted)} ${label}`);
    if (choice.description) {
      console.log(`      ${paint(choice.description, focused ? t.blue : t.muted)}`);
    }
    if (choice.hint) {
      console.log(`      ${paint(choice.hint, t.gold)}`);
    }
    if (idx < choices.length - 1) console.log("");
  });
}

async function askChoice(rl, title, choices, subtitle = "交互式安装") {
  if (process.stdin.isTTY && process.stdout.isTTY) {
    return await new Promise((resolve) => {
      let index = 0;
      const stdin = process.stdin;

      function cleanup(value) {
        stdin.off("data", onData);
        if (stdin.isTTY) stdin.setRawMode(false);
        stdin.pause();
        clearScreen();
        resolve(value);
      }

      function onKey(key = {}) {
        if (key.ctrl && key.name === "c") return cleanup("exit");
        if (key.name === "q" || key.name === "escape") return cleanup("exit");
        if (key.name === "up") {
          index = (index - 1 + choices.length) % choices.length;
          renderChoiceScreen(title, choices, index, subtitle);
          return;
        }
        if (key.name === "down") {
          index = (index + 1) % choices.length;
          renderChoiceScreen(title, choices, index, subtitle);
          return;
        }
        if (key.name === "return" || key.name === "enter") return cleanup(choices[index].value);
        if (key.name === "number" && choices[key.number - 1]) return cleanup(choices[key.number - 1].value);
      }

      function onData(chunk) {
        onKey(readRawKey(chunk));
      }

      if (stdin.isTTY) stdin.setRawMode(true);
      stdin.on("data", onData);
      stdin.resume();
      renderChoiceScreen(title, choices, index, subtitle);
    });
  }

  console.log("");
  console.log(title);
  choices.forEach((choice, index) => {
    console.log(`  ${index + 1}. ${choice.label}`);
    if (choice.description) console.log(`     ${choice.description}`);
    if (choice.hint) console.log(`     ${choice.hint}`);
  });
  while (true) {
    const answer = (await rl.question("> ")).trim().toLowerCase();
    const index = Number.parseInt(answer, 10) - 1;
    if (Number.isInteger(index) && choices[index]) return choices[index].value;
    const byValue = choices.find((choice) => choice.value === answer);
    if (byValue) return byValue.value;
    console.log("请输入上面列出的数字或选项名称。");
  }
}

function renderMultiChoiceScreen(title, choices, index, selected, subtitle) {
  renderHeader(subtitle);
  console.log("");
  console.log(paint(title, t.bold, t.blue));
  console.log("");
  choices.forEach((choice, idx) => {
    const focused = idx === index;
    const checked = selected.has(choice.value);
    const box = checked ? paint("[✓]", t.teal, t.bold) : paint("[ ]", t.muted);
    const cursor = focused ? paint(">", t.teal, t.bold) : " ";
    const label = focused
      ? paint(` ${choice.label} `, t.bold, t.selectedFg, t.selectedBg)
      : paint(choice.label, t.bold);
    console.log(` ${cursor} ${box} ${label}`);
    if (choice.description) {
      console.log(`      ${paint(choice.description, focused ? t.blue : t.muted)}`);
    }
    if (choice.hint) {
      console.log(`      ${paint(choice.hint, t.gold)}`);
    }
    if (idx < choices.length - 1) console.log("");
  });
}

async function askMultiChoice(rl, title, choices, subtitle = "交互式安装") {
  if (process.stdin.isTTY && process.stdout.isTTY) {
    return await new Promise((resolve) => {
      let index = 0;
      const selected = new Set();
      const stdin = process.stdin;

      function cleanup(value) {
        stdin.off("data", onData);
        if (stdin.isTTY) stdin.setRawMode(false);
        stdin.pause();
        clearScreen();
        resolve(value);
      }

      function toggle() {
        const value = choices[index].value;
        if (selected.has(value)) selected.delete(value);
        else selected.add(value);
        renderMultiChoiceScreen(title, choices, index, selected, subtitle);
      }

      function onKey(key = {}) {
        if (key.ctrl && key.name === "c") return cleanup([]);
        if (key.name === "q" || key.name === "escape") return cleanup([]);
        if (key.name === "up") {
          index = (index - 1 + choices.length) % choices.length;
          renderMultiChoiceScreen(title, choices, index, selected, subtitle);
          return;
        }
        if (key.name === "down") {
          index = (index + 1) % choices.length;
          renderMultiChoiceScreen(title, choices, index, selected, subtitle);
          return;
        }
        if (key.name === "space") return toggle();
        if (key.name === "return" || key.name === "enter") return cleanup([...selected]);
        if (key.name === "number" && choices[key.number - 1]) {
          index = key.number - 1;
          toggle();
        }
      }

      function onData(chunk) {
        onKey(readRawKey(chunk));
      }

      if (stdin.isTTY) stdin.setRawMode(true);
      stdin.on("data", onData);
      stdin.resume();
      renderMultiChoiceScreen(title, choices, index, selected, subtitle);
    });
  }

  console.log("");
  console.log(title);
  choices.forEach((choice, index) => {
    console.log(`  ${index + 1}. ${choice.label}`);
    if (choice.description) console.log(`     ${choice.description}`);
    if (choice.hint) console.log(`     ${choice.hint}`);
  });
  const answer = await rl.question("请输入要选择的数字,多个数字用逗号分隔;直接回车表示不选择 > ");
  return answer
    .split(/[, ]+/)
    .map((item) => Number.parseInt(item, 10) - 1)
    .filter((index) => Number.isInteger(index) && choices[index])
    .map((index) => choices[index].value);
}

async function askEmail(rl) {
  const envEmail = process.env.OHAI_INSTALL_USER_EMAIL || "";
  const hint = emailIsValid(envEmail) ? ` [${envEmail}]` : "";
  renderHeader("问题反馈插件设置");
  console.log("");
  console.log(paint("公司邮箱", t.bold, t.blue));
  console.log(paint("中文提示:用于问题反馈中的提交人标识;不填写也可以继续安装。", t.muted));
  console.log(paint("示例:xxxxx@huawei.com 或 xxxxx@h-partners.com", t.muted));
  console.log(paint("直接回车表示暂不配置邮箱。", t.muted));
  console.log("");
  while (true) {
    const answer = (await rl.question(`${paint("公司邮箱", t.cyan)}${paint(hint, t.muted)} > `)).trim();
    const value = answer || (emailIsValid(envEmail) ? envEmail.trim() : "");
    if (!value) return "";
    if (emailIsValid(value)) return value;
    console.log(paint("邮箱格式不正确。示例:xxxxx@huawei.com 或 xxxxx@h-partners.com", t.red));
  }
}

async function collectInstallPlan(rl) {
  const mainCategory = await askChoice(
    null,
    "请选择要执行的操作(单选)",
    [
      {
        label: "Langfuse",
        value: "langfuse",
        description: "配置/更新 Langfuse 运行追踪。",
        hint: "适用:想在 Langfuse 中查看 AI 运行记录、工具调用和 token 用量时选择。",
      },
      {
        label: "SkillHub (OpenHarmony)",
        value: "skill",
        description: "安装或卸载 OpenHarmony Skill。",
        hint: "适用:需要在 AI 编码工具中使用 OpenHarmony 开发规范、测试生成等 Skill 时选择。",
      },
      {
        label: "问题反馈插件",
        value: "report",
        description: "安装 /report-ai-issue 命令,用于提交 AI 编码问题反馈。",
        hint: "适用:需要在 OpenCode 或 Claude Code 中主动上报问题时选择。",
      },
    ],
    "安装菜单"
  );

  if (mainCategory === "exit" || !mainCategory) return { mainCategory: "", subActions: [], reportTarget: "" };

  let subActions = [];
  let reportTarget = "";

  if (mainCategory === "langfuse") {
    const langfuseSubs = await askMultiChoice(
      null,
      "请选择 Langfuse 子功能(Space 多选,Enter 继续)",
      [
        {
          label: "Langfuse 追踪配置",
          value: "langfuse",
          description: "为 Claude Code、OpenCode 或 Codex 配置 Langfuse 运行追踪。",
        },
        {
          label: "更新 Langfuse 运行时",
          value: "langfuse-update",
          description: "更新已安装的 Langfuse hooks/plugins 到最新发布版本。",
        },
      ],
      "Langfuse 设置"
    );
    if (langfuseSubs.length) {
      subActions = langfuseSubs;
    }
  }

  if (mainCategory === "skill") {
    const skillSubs = await askMultiChoice(
      null,
      "请选择 SkillHub 功能(Space 多选,Enter 继续)",
      [
        {
          label: "Skill 安装 (OpenHarmony)",
          value: "skill",
          description: "浏览 OpenHarmony Skill 分组,选择安装到 Codex/Claude/OpenCode。",
        },
        {
          label: "Skill 卸载 (OpenHarmony)",
          value: "skill-clean",
          description: "卸载已安装的 OpenHarmony Skill。",
        },
      ],
      "SkillHub 设置"
    );
    if (skillSubs.length) {
      subActions = skillSubs;
    }
  }

  if (mainCategory === "report") {
    const targets = await askMultiChoice(
      null,
      "请选择问题反馈插件安装目标(Space 多选,Enter 继续)",
      [
        {
          label: "OpenCode 问题反馈",
          value: "opencode",
          description: "中文提示:安装 OpenCode 插件和 /report-ai-issue 命令。",
          hint: "适用:主要在 OpenCode 中使用问题反馈功能时选择。",
        },
        {
          label: "Claude Code 问题反馈",
          value: "claude",
          description: "中文提示:安装 Claude Code 命令和可选 hook 集成。",
          hint: "适用:主要在 Claude Code 中使用问题反馈功能时选择。",
        },
        {
          label: "Codex 问题反馈",
          value: "codex",
          description: "中文提示:安装 Codex skill 和 PowerShell wrapper。",
          hint: "适用:主要在 Codex 中使用问题反馈功能时选择。",
        },
      ],
      "问题反馈插件设置"
    );
    if (targets.length) {
      reportTarget = targets.length === 3 ? "all" : targets.length === 2 && !targets.includes("codex") ? "both" : targets.join(",");
    }
  }

  return { mainCategory, subActions, reportTarget };
}

async function runInteractiveInstall() {
  if (!process.stdin.isTTY) {
    printHelp();
    return 0;
  }

  const plan = await collectInstallPlan();

  let code = 0;
  if (plan.mainCategory === "langfuse" && plan.subActions.length) {
    if (plan.subActions.includes("langfuse")) {
      code = code || runNodeScript(langfuseCli, ["setup"]);
    }
    if (plan.subActions.includes("langfuse-update")) {
      code = code || runNodeScript(langfuseCli, ["update", "all"]);
    }
    prepareStdinForChildProcess();
  }
  if (plan.mainCategory === "skill" && plan.subActions.length) {
    if (plan.subActions.includes("skill")) {
      code = code || runNodeScript(skillhubCli, []);
    }
    if (plan.subActions.includes("skill-clean")) {
      code = code || runNodeScript(skillhubCli, ["clean"]);
    }
    prepareStdinForChildProcess();
  }
  if (plan.mainCategory === "report" && plan.reportTarget) {
    const reportTargets = String(plan.reportTarget).split(",").filter(Boolean);
    for (const target of reportTargets) {
      const args = ["install", target];
      code = code || runNodeScript(reportCli, args);
    }
  }
  return code;
}

async function main() {
  const argv = process.argv.slice(2);
  const [cmd, ...rest] = argv;

  if (cmd === "--help" || cmd === "-h" || cmd === "help") {
    printHelp();
    return 0;
  }

  if (!cmd) return await runInteractiveInstall();

  if (cmd === "langfuse" || cmd === "trace" || cmd === "tracing") {
    return runNodeScript(langfuseCli, rest);
  }

  if (cmd === "report" || cmd === "ohai" || cmd === "issue") {
    return runNodeScript(reportCli, rest);
  }

  if (cmd === "setup" || cmd === "check") {
    return runNodeScript(langfuseCli, argv);
  }

  if (cmd === "skill" || cmd === "skillhub") {
    return runNodeScript(skillhubCli, rest);
  }

  if (cmd === "skill-clean" || cmd === "skill-uninstall") {
    return runNodeScript(skillhubCli, ["clean"]);
  }

  console.error(`未知命令: ${cmd}`);
  console.error("");
  printHelp();
  return 1;
}

assertSupportedNode();

main()
  .then((code) => process.exit(code))
  .catch((err) => {
    console.error(paint((err && err.message) || String(err), t.red));
    process.exit(1);
  });