'use strict';

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

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

var readline__default = /*#__PURE__*/_interopDefault(readline);

// src/platform/core/helpers.ts
function normalizePromptPathInput(value) {
  let normalized = value.trim();
  while (normalized.length >= 2 && (normalized.startsWith("`") && normalized.endsWith("`") || normalized.startsWith('"') && normalized.endsWith('"') || normalized.startsWith("'") && normalized.endsWith("'"))) {
    normalized = normalized.slice(1, -1).trim();
  }
  return normalized;
}
var ANSI = {
  dim: "\x1B[2m",
  reset: "\x1B[0m"};
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 getTerminalColumns() {
  return Math.max(process$1.stdout.columns || 100, 4);
}
function wrapPlainText(value, firstLineWidth, continuationLineWidth) {
  const renderedLines = [];
  const safeFirstLineWidth = Math.max(firstLineWidth, 1);
  const safeContinuationLineWidth = Math.max(continuationLineWidth, 1);
  const normalizedValue = value.replace(/\r\n?/g, "\n");
  const pushWrappedLine = (line) => {
    if (line.length === 0) {
      renderedLines.push("");
      return;
    }
    let currentLine = "";
    let currentWidth = 0;
    let currentLineWidth = renderedLines.length === 0 ? safeFirstLineWidth : safeContinuationLineWidth;
    for (const segment of segmentGraphemes(line)) {
      const segmentWidth = Math.max(getGraphemeWidth(segment), 1);
      if (currentLine && currentWidth + segmentWidth > currentLineWidth) {
        renderedLines.push(currentLine);
        currentLine = "";
        currentWidth = 0;
        currentLineWidth = safeContinuationLineWidth;
      }
      currentLine += segment;
      currentWidth += segmentWidth;
    }
    renderedLines.push(currentLine);
  };
  normalizedValue.split("\n").forEach(pushWrappedLine);
  return renderedLines.length > 0 ? renderedLines : [""];
}
function buildPromptRenderLayout(promptLabel, buffer, placeholder) {
  const columns = getTerminalColumns();
  const promptLabelWidth = visibleLength(promptLabel);
  const continuationIndentWidth = Math.min(promptLabelWidth, Math.max(columns - 1, 0));
  const continuationIndent = " ".repeat(continuationIndentWidth);
  const firstLineWidth = Math.max(columns - promptLabelWidth, 1);
  const continuationLineWidth = Math.max(columns - continuationIndentWidth, 1);
  const hasBuffer = buffer.length > 0;
  const contentLines = hasBuffer ? wrapPlainText(buffer, firstLineWidth, continuationLineWidth) : wrapPlainText("", firstLineWidth, continuationLineWidth);
  const cursorLines = hasBuffer ? contentLines : [""];
  const renderedPromptLines = contentLines.map((line, index) => {
    const linePrefix = index === 0 ? promptLabel : continuationIndent;
    return `${linePrefix}${hasBuffer ? line : colorize(line, ANSI.dim)}`;
  });
  const activeCursorLine = cursorLines.at(-1) || "";
  const activeCursorLinePrefixWidth = cursorLines.length <= 1 ? promptLabelWidth : continuationIndentWidth;
  return {
    cursorColumn: activeCursorLinePrefixWidth + visibleLength(activeCursorLine),
    cursorRowOffset: Math.max(cursorLines.length - 1, 0),
    lines: renderedPromptLines,
    totalLines: renderedPromptLines.length
  };
}
function clearRenderedPrompt(previousState) {
  if (previousState?.cursorRowOffset) {
    readline__default.default.moveCursor(process$1.stdout, 0, -previousState.cursorRowOffset);
  }
  readline__default.default.cursorTo(process$1.stdout, 0);
  readline__default.default.clearScreenDown(process$1.stdout);
}
function renderPromptLayout(layout, previousState) {
  clearRenderedPrompt(previousState);
  process$1.stdout.write(layout.lines.join("\n"));
  const linesBelowCursor = layout.totalLines - 1 - layout.cursorRowOffset;
  if (linesBelowCursor > 0) {
    readline__default.default.moveCursor(process$1.stdout, 0, -linesBelowCursor);
  }
  readline__default.default.cursorTo(process$1.stdout, layout.cursorColumn);
  return {
    cursorRowOffset: layout.cursorRowOffset,
    totalLines: layout.totalLines
  };
}
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);
}

// src/platform/ui/prompt.ts
function renderQuestionPrompt(question, buffer, previousState) {
  return renderPromptLayout(buildPromptRenderLayout(question, buffer), previousState);
}
async function askQuestion(question) {
  return new Promise((resolve, reject) => {
    const { stdin } = process;
    const rawState = "isRaw" in stdin ? Boolean(stdin.isRaw) : false;
    let buffer = "";
    const cleanup = () => {
      stdin.removeListener("keypress", onKeyPress);
      if (stdin.isTTY) {
        stdin.setRawMode(rawState);
      }
      stdin.pause();
    };
    let renderState;
    const onKeyPress = (input, key) => {
      if (key.ctrl && key.name === "c") {
        clearRenderedPrompt(renderState);
        cleanup();
        reject(createUserTerminatedError("\uC0AC\uC6A9\uC790\uAC00 \uC9C8\uBB38 \uC785\uB825 \uC911 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "escape") {
        clearRenderedPrompt(renderState);
        cleanup();
        reject(createUserCancelledError("\uC0AC\uC6A9\uC790\uAC00 \uC9C8\uBB38 \uC785\uB825\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "return" || key.name === "enter") {
        const resolved = buffer.trim();
        clearRenderedPrompt(renderState);
        cleanup();
        console.log(`${question}${resolved}`);
        appendSlashCommandTelemetryInputValue(resolved);
        resolve(resolved);
        return;
      }
      if (key.name === "backspace") {
        if (buffer.length > 0) {
          buffer = buffer.slice(0, -1);
          renderState = renderQuestionPrompt(question, buffer, renderState);
        }
        return;
      }
      if (input && !key.ctrl && !key.meta) {
        buffer += input;
        renderState = renderQuestionPrompt(question, buffer, renderState);
      }
    };
    readline__default.default.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    renderState = renderQuestionPrompt(question, buffer);
  });
}
function normalizeGenHtmlComponentName(componentName) {
  return componentName.trim();
}
function normalizeGenHtmlReferenceInput(reference) {
  return {
    description: reference.description.trim(),
    figmaAddress: reference.figmaAddress.trim()
  };
}
function normalizeGenHtmlComponentInput(component) {
  return {
    componentName: normalizeGenHtmlComponentName(component.componentName),
    references: component.references.map(normalizeGenHtmlReferenceInput).filter((reference) => Boolean(reference.figmaAddress))
  };
}
function formatGenHtmlComponentInputMarkdown(component) {
  const normalizedComponent = normalizeGenHtmlComponentInput(component);
  return [
    `- componentName: \`${normalizedComponent.componentName}\``,
    `- referenceCount: \`${normalizedComponent.references.length}\``,
    normalizedComponent.references.length > 0 ? normalizedComponent.references.map(
      (reference, index) => [
        `- [${index + 1}] figmaAddress: \`${reference.figmaAddress}\``,
        reference.description ? `  description: ${reference.description}` : "  description: (\uC5C6\uC74C)"
      ].join("\n")
    ).join("\n") : "- references: (\uC5C6\uC74C)"
  ].join("\n");
}

// src/features/gen-html/application/input.ts
function parseYesNoAnswer(value, defaultValue) {
  const normalizedValue = normalizePromptPathInput(value).toLowerCase();
  if (!normalizedValue) {
    return defaultValue;
  }
  if (["y", "yes", "true", "1", "\u3147", "\uC608"].includes(normalizedValue)) {
    return true;
  }
  if (["n", "no", "false", "0", "\u3134", "\uC544\uB2C8\uC624"].includes(normalizedValue)) {
    return false;
  }
  return defaultValue;
}
async function collectGenHtmlComponentInputFromTerminal(trace) {
  trace?.("gen-html:input:start");
  const componentName = normalizePromptPathInput(await askQuestion("\uC0DD\uC131\uD560 \uCEF4\uD3EC\uB10C\uD2B8\uBA85\uC744 \uC785\uB825\uD558\uC138\uC694: "));
  if (!componentName) {
    trace?.("gen-html:input:cancelled", "empty-component-name");
    console.log("\uCEF4\uD3EC\uB10C\uD2B8\uBA85\uC774 \uBE44\uC5B4 \uC788\uC5B4 \uC791\uC5C5\uC744 \uCDE8\uC18C\uD569\uB2C8\uB2E4.");
    return void 0;
  }
  const references = [];
  let referenceIndex = 0;
  let shouldCollectReference = true;
  while (shouldCollectReference) {
    referenceIndex += 1;
    const figmaAddress = normalizePromptPathInput(await askQuestion(`\uCC38\uC870\uD560 Figma \uC8FC\uC18C ${referenceIndex}\uB97C \uC785\uB825\uD558\uC138\uC694: `));
    if (!figmaAddress) {
      if (references.length === 0) {
        trace?.("gen-html:input:cancelled", "missing-first-reference");
        console.log("\uCD5C\uC18C 1\uAC1C\uC758 Figma \uC8FC\uC18C\uAC00 \uD544\uC694\uD574 \uC791\uC5C5\uC744 \uCDE8\uC18C\uD569\uB2C8\uB2E4.");
        return void 0;
      }
      trace?.("gen-html:input:references:complete", `count=${references.length}`);
      console.log("\uC8FC\uC18C\uAC00 \uBE44\uC5B4 \uC788\uC5B4 \uCD94\uAC00 \uC785\uB825\uC744 \uC885\uB8CC\uD569\uB2C8\uB2E4.");
      break;
    }
    const description = normalizePromptPathInput(
      await askQuestion(`Figma \uC8FC\uC18C ${referenceIndex} \uC124\uBA85\uC744 \uC785\uB825\uD558\uC138\uC694 (\uC608: \uAE30\uBCF8 \uC0C1\uD0DC / \uC5D0\uB7EC \uC0C1\uD0DC / \uCF54\uBA58\uD2B8): `)
    );
    references.push({
      description,
      figmaAddress
    });
    trace?.("gen-html:input:reference:added", `index=${referenceIndex} hasDescription=${String(Boolean(description))}`);
    shouldCollectReference = parseYesNoAnswer(await askQuestion("Figma \uCC38\uC870\uB97C \uB354 \uCD94\uAC00\uD560\uAE4C\uC694? (y/N): "), false);
    if (!shouldCollectReference) {
      trace?.("gen-html:input:references:complete", `count=${references.length}`);
    }
  }
  const component = normalizeGenHtmlComponentInput({
    componentName,
    references
  });
  console.log("\uC785\uB825 \uC694\uC57D");
  console.log(formatGenHtmlComponentInputMarkdown(component));
  const shouldExecute = parseYesNoAnswer(await askQuestion("\uC774 \uC785\uB825\uC73C\uB85C \uC2E4\uD589\uD560\uAE4C\uC694? (Y/n): "), true);
  if (!shouldExecute) {
    trace?.("gen-html:input:cancelled", "confirmation-declined");
    console.log("\uC0AC\uC6A9\uC790 \uC694\uCCAD\uC73C\uB85C \uC2E4\uD589\uC744 \uCDE8\uC18C\uD569\uB2C8\uB2E4.");
    return void 0;
  }
  trace?.("gen-html:input:end", `component=${component.componentName} references=${component.references.length}`);
  return component;
}

exports.collectGenHtmlComponentInputFromTerminal = collectGenHtmlComponentInputFromTerminal;
