'use strict';

var readline2 = require('readline');
require('os');
require('posthog-node');
require('fs');
require('path');
require('child_process');
require('util');
var process$1 = require('process');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var readline2__default = /*#__PURE__*/_interopDefault(readline2);

// src/platform/ui/selector.ts

// src/platform/analytics/posthog.ts
var telemetryRuntimeState = globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ ?? (globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ = {});
function appendSlashCommandTelemetryInputValue(value) {
  if (!telemetryRuntimeState.slashCommandTelemetryInputValues) {
    return;
  }
  telemetryRuntimeState.slashCommandTelemetryInputValues.push(...normalizeSlashCommandTelemetryValues(value));
}
function normalizeSlashCommandTelemetryValues(value) {
  if (value === void 0) {
    return [];
  }
  if (value === null) {
    return [null];
  }
  if (Array.isArray(value)) {
    return value.flatMap((item) => normalizeSlashCommandTelemetryValues(item));
  }
  if (typeof value === "string") {
    return [value];
  }
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return [String(value)];
  }
  if (typeof value === "object") {
    const objectValue = value;
    if (typeof objectValue.url === "string" && objectValue.url) {
      return [objectValue.url];
    }
    if (typeof objectValue.hash === "string" && objectValue.hash) {
      return [objectValue.hash];
    }
    if (typeof objectValue.name === "string" && objectValue.name) {
      return [objectValue.name];
    }
    if (typeof objectValue.label === "string" && objectValue.label) {
      return [objectValue.label];
    }
    try {
      return [JSON.stringify(objectValue)];
    } catch {
      return ["[object]"];
    }
  }
  return [String(value)];
}

// src/platform/core/cancellation.ts
var USER_CANCELLED_ERROR_CODE = "JUHONG_E_USER_CANCELLED";
var USER_TERMINATED_ERROR_CODE = "JUHONG_E_USER_TERMINATED";
function createCancellationError(name, code, message) {
  const error = new Error(message);
  error.name = name;
  error.code = code;
  return error;
}
function createUserCancelledError(message = "\uC0AC\uC6A9\uC790\uAC00 \uD604\uC7AC \uC791\uC5C5\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4.") {
  return createCancellationError("UserCancelledError", USER_CANCELLED_ERROR_CODE, message);
}
function createUserTerminatedError(message = "\uC0AC\uC6A9\uC790\uAC00 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4.") {
  return createCancellationError("UserTerminatedError", USER_TERMINATED_ERROR_CODE, message);
}
var ANSI = {
  bold: "\x1B[1m",
  gray: "\x1B[90m",
  green: "\x1B[32m",
  reset: "\x1B[0m",
  yellow: "\x1B[33m"
};
var ANSI_PATTERN = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
var COMBINING_MARK_PATTERN = /\p{Mark}/u;
var GRAPHEME_SEGMENTER = typeof Intl !== "undefined" && "Segmenter" in Intl ? new Intl.Segmenter("ko", { granularity: "grapheme" }) : null;
function colorize(text, color) {
  return `${color}${text}${ANSI.reset}`;
}
function segmentGraphemes(value) {
  if (!GRAPHEME_SEGMENTER) {
    return [...value];
  }
  return [...GRAPHEME_SEGMENTER.segment(value)].map(({ segment }) => segment);
}
function getGraphemeWidth(grapheme) {
  let width = 0;
  for (const character of grapheme) {
    const codePoint = character.codePointAt(0);
    if (!codePoint || COMBINING_MARK_PATTERN.test(character) || codePoint === 8205) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039 || codePoint >= 917760 && codePoint <= 917999) {
      continue;
    }
    if (isWideCodePoint(codePoint) || isEmojiCodePoint(codePoint)) {
      width = Math.max(width, 2);
      continue;
    }
    width = Math.max(width, 1);
  }
  return width;
}
function tokenizePlainText(value) {
  return segmentGraphemes(value).map((segment) => ({
    value: segment,
    visibleWidth: getGraphemeWidth(segment)
  }));
}
function tokenizeVisibleText(value) {
  const tokens = [];
  let lastIndex = 0;
  for (const match of value.matchAll(ANSI_PATTERN)) {
    const index = match.index ?? 0;
    if (index > lastIndex) {
      tokens.push(...tokenizePlainText(value.slice(lastIndex, index)));
    }
    tokens.push({
      value: match[0],
      visibleWidth: 0
    });
    lastIndex = index + match[0].length;
  }
  if (lastIndex < value.length) {
    tokens.push(...tokenizePlainText(value.slice(lastIndex)));
  }
  return tokens;
}
function isWideCodePoint(codePoint) {
  return codePoint >= 4352 && (codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || codePoint >= 11904 && codePoint <= 12871 && codePoint !== 12351 || codePoint >= 12880 && codePoint <= 19903 || codePoint >= 19968 && codePoint <= 42182 || codePoint >= 43360 && codePoint <= 43388 || codePoint >= 44032 && codePoint <= 55203 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65040 && codePoint <= 65049 || codePoint >= 65072 && codePoint <= 65131 || codePoint >= 65281 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510 || codePoint >= 127488 && codePoint <= 127569 || codePoint >= 131072 && codePoint <= 262141);
}
function isEmojiCodePoint(codePoint) {
  return codePoint >= 127462 && codePoint <= 127487 || codePoint >= 127744 && codePoint <= 129791 || codePoint >= 9728 && codePoint <= 10175;
}
function visibleLength(value) {
  return tokenizeVisibleText(value).reduce((total, token) => total + token.visibleWidth, 0);
}
function sliceVisible(value, width) {
  if (width <= 0) {
    return "";
  }
  let currentWidth = 0;
  let output = "";
  let truncated = false;
  let containsAnsi = false;
  for (const token of tokenizeVisibleText(value)) {
    if (token.visibleWidth === 0) {
      output += token.value;
      containsAnsi = true;
      continue;
    }
    if (currentWidth + token.visibleWidth > width) {
      truncated = true;
      break;
    }
    output += token.value;
    currentWidth += token.visibleWidth;
  }
  if (truncated && containsAnsi && !output.endsWith(ANSI.reset)) {
    output += ANSI.reset;
  }
  return output;
}
function padVisible(value, width) {
  const slicedValue = sliceVisible(value, width);
  const length = visibleLength(slicedValue);
  if (length >= width) {
    return slicedValue;
  }
  return `${slicedValue}${" ".repeat(width - length)}`;
}
function truncateValue(value, width) {
  if (visibleLength(value) <= width) {
    return value;
  }
  if (width <= 3) {
    return sliceVisible(value, width);
  }
  return `${sliceVisible(value, width - 3)}...`;
}
function getViewportWidth() {
  const columns = process$1.stdout.columns || 100;
  return Math.max(Math.min(columns - 2, 108), 4);
}
function createBox(title, lines, footerLines = []) {
  const contentLines = lines.length > 0 ? lines : [""];
  const footer = footerLines.length > 0 ? ["", ...footerLines] : [];
  const width = getViewportWidth();
  const top = `+${"-".repeat(width - 2)}+`;
  const titleLine = `| ${padVisible(colorize(title, ANSI.bold), width - 4)} |`;
  const body = [...contentLines, ...footer].map((line) => `| ${padVisible(line, width - 4)} |`);
  return [top, titleLine, top, ...body, top];
}
function renderScreenBox(title, lines, footerLines = []) {
  console.clear();
  console.log(createBox(title, lines, footerLines).join("\n"));
}

// src/platform/ui/selector.ts
var SINGLE_OPTION_PREFIX_WIDTH = 2;
var SINGLE_OPTION_GAP_WIDTH = 1;
var SINGLE_OPTION_MIN_LABEL_WIDTH = 8;
var SINGLE_OPTION_LABEL_PADDING = 2;
function computeSingleOptionColumnWidths(options) {
  const boxInnerWidth = getViewportWidth() - 4;
  const maxLabelCellWidth = Math.max(
    SINGLE_OPTION_MIN_LABEL_WIDTH,
    ...options.map((option) => visibleLength(option.label) + SINGLE_OPTION_LABEL_PADDING)
  );
  const labelWidth = Math.min(maxLabelCellWidth, Math.floor(boxInnerWidth * 0.5));
  const descriptionWidth = Math.max(0, boxInnerWidth - SINGLE_OPTION_PREFIX_WIDTH - labelWidth - SINGLE_OPTION_GAP_WIDTH);
  return { descriptionWidth, labelWidth };
}
function selectSingleOption(title, options) {
  return new Promise((resolve, reject) => {
    if (options.length === 0) {
      reject(new Error("\uC120\uD0DD \uAC00\uB2A5\uD55C \uD56D\uBAA9\uC774 \uC5C6\uC2B5\uB2C8\uB2E4."));
      return;
    }
    const { stdin } = process;
    const rawState = "isRaw" in stdin ? Boolean(stdin.isRaw) : false;
    let cursor = 0;
    const cleanup = () => {
      stdin.removeListener("keypress", onKeyPress);
      if (stdin.isTTY) {
        stdin.setRawMode(rawState);
      }
      stdin.pause();
      console.clear();
    };
    const { labelWidth, descriptionWidth } = computeSingleOptionColumnWidths(options);
    const render = () => {
      renderScreenBox(
        title,
        options.map((option, index) => {
          const prefix = cursor === index ? colorize(">", ANSI.green) : " ";
          const label = cursor === index ? colorize(option.label, ANSI.green) : option.label;
          const description = option.description ? truncateValue(option.description, descriptionWidth) : "";
          return `${prefix} ${padVisible(label, labelWidth)} ${colorize(description, ANSI.gray)}`;
        }),
        [
          `${colorize("Up/Down", ANSI.yellow)} \uC774\uB3D9`,
          `${colorize("Enter", ANSI.yellow)} \uC120\uD0DD`,
          `${colorize("ESC", ANSI.yellow)} \uCDE8\uC18C`,
          `${colorize("Ctrl+C", ANSI.yellow)} \uC138\uC158 \uC885\uB8CC`
        ]
      );
    };
    const onKeyPress = (_input, key) => {
      if (key.ctrl && key.name === "c") {
        cleanup();
        reject(createUserTerminatedError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825 \uC911 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "escape") {
        cleanup();
        reject(createUserCancelledError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "up") {
        cursor = cursor === 0 ? options.length - 1 : cursor - 1;
        render();
        return;
      }
      if (key.name === "down") {
        cursor = cursor === options.length - 1 ? 0 : cursor + 1;
        render();
        return;
      }
      if (key.name === "return" || key.name === "enter") {
        const selected = options[cursor];
        if (!selected) {
          cleanup();
          reject(new Error("\uC120\uD0DD\uD55C \uD56D\uBAA9\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4."));
          return;
        }
        cleanup();
        appendSlashCommandTelemetryInputValue(selected.value);
        resolve(selected.value);
      }
    };
    readline2__default.default.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    render();
  });
}
function selectMultipleOptions(title, options, windowSize = 10) {
  return new Promise((resolve, reject) => {
    if (options.length === 0) {
      resolve([]);
      return;
    }
    const { stdin } = process;
    const rawState = "isRaw" in stdin ? Boolean(stdin.isRaw) : false;
    let cursor = 0;
    const selectedIndexes = /* @__PURE__ */ new Set();
    const cleanup = () => {
      stdin.removeListener("keypress", onKeyPress);
      if (stdin.isTTY) {
        stdin.setRawMode(rawState);
      }
      stdin.pause();
      console.clear();
    };
    const render = () => {
      const start = Math.max(0, Math.min(cursor - Math.floor(windowSize / 2), Math.max(options.length - windowSize, 0)));
      const visibleOptions = options.slice(start, start + windowSize);
      renderScreenBox(
        title,
        [
          `${colorize("\uD45C\uC2DC \uBC94\uC704", ANSI.gray)} ${start + 1}-${Math.min(start + windowSize, options.length)} / ${options.length}`,
          `${colorize("\uC120\uD0DD \uAC1C\uC218", ANSI.gray)} ${selectedIndexes.size}`,
          ""
        ].concat(
          visibleOptions.map((option, offset) => {
            const index = start + offset;
            const isActive = cursor === index;
            const isSelected = selectedIndexes.has(index);
            const prefix = isActive ? colorize(">", ANSI.green) : " ";
            const checked = isSelected ? colorize("[x]", ANSI.green) : "[ ]";
            const label = isActive ? colorize(truncateValue(option.label, 54), ANSI.green) : truncateValue(option.label, 54);
            const description = option.description ? colorize(truncateValue(option.description, 28), ANSI.gray) : "";
            return `${prefix} ${checked} ${padVisible(label, 56)} ${description}`;
          })
        ),
        [
          `${colorize("Up/Down", ANSI.yellow)} \uC774\uB3D9`,
          `${colorize("Space", ANSI.yellow)} \uC120\uD0DD/\uD574\uC81C`,
          `${colorize("Enter", ANSI.yellow)} \uC644\uB8CC`,
          `${colorize("ESC", ANSI.yellow)} \uCDE8\uC18C`,
          `${colorize("Ctrl+C", ANSI.yellow)} \uC138\uC158 \uC885\uB8CC`
        ]
      );
    };
    const onKeyPress = (_input, key) => {
      if (key.ctrl && key.name === "c") {
        cleanup();
        reject(createUserTerminatedError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825 \uC911 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "escape") {
        cleanup();
        reject(createUserCancelledError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "up") {
        cursor = cursor === 0 ? options.length - 1 : cursor - 1;
        render();
        return;
      }
      if (key.name === "down") {
        cursor = cursor === options.length - 1 ? 0 : cursor + 1;
        render();
        return;
      }
      if (key.name === "space") {
        if (selectedIndexes.has(cursor)) {
          selectedIndexes.delete(cursor);
        } else {
          selectedIndexes.add(cursor);
        }
        render();
        return;
      }
      if (key.name === "return" || key.name === "enter") {
        const resolvedValues = [...selectedIndexes].sort((left, right) => left - right).flatMap((index) => {
          const option = options[index];
          return option ? [option.value] : [];
        });
        cleanup();
        appendSlashCommandTelemetryInputValue(resolvedValues);
        resolve(resolvedValues);
      }
    };
    readline2__default.default.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    render();
  });
}

exports.selectMultipleOptions = selectMultipleOptions;
exports.selectSingleOption = selectSingleOption;
