'use strict';

var path3 = require('path');
var fs4 = require('fs');
require('child_process');
require('util');
var url = require('url');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var path3__default = /*#__PURE__*/_interopDefault(path3);
var fs4__default = /*#__PURE__*/_interopDefault(fs4);

// src/features/gen-storybook/application/prompt.ts
function safeExcerpt(content, limit = 3e3) {
  if (!content) {
    return "";
  }
  if (content.length <= limit) {
    return content;
  }
  return `${content.slice(0, limit)}
... (truncated ${content.length - limit} chars)`;
}
var PACKAGE_JSON_FILE_NAME = "package.json";
function findPackageRoot(moduleFilePath) {
  let currentDirectoryPath = path3__default.default.dirname(moduleFilePath);
  while (!fs4__default.default.existsSync(path3__default.default.join(currentDirectoryPath, PACKAGE_JSON_FILE_NAME))) {
    const parentDirectoryPath = path3__default.default.dirname(currentDirectoryPath);
    if (parentDirectoryPath === currentDirectoryPath) {
      throw new Error(`markdown \uC790\uC0B0 package root\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. start=${moduleFilePath}`);
    }
    currentDirectoryPath = parentDirectoryPath;
  }
  return currentDirectoryPath;
}
function resolvePromptPackageFilePath(importMetaUrl, packageRelativeFilePath) {
  const moduleFilePath = url.fileURLToPath(importMetaUrl);
  const packageRoot = findPackageRoot(moduleFilePath);
  return path3__default.default.normalize(path3__default.default.resolve(packageRoot, packageRelativeFilePath));
}
function createPromptMarkdownFileAsset(importMetaUrl, packageRelativeFilePath) {
  return {
    filePath: resolvePromptPackageFilePath(importMetaUrl, packageRelativeFilePath),
    kind: "file-reference"
  };
}
function isPromptMarkdownFileReference(asset) {
  return typeof asset !== "string";
}
function isPromptRuleGroupAsset(asset) {
  return typeof asset !== "string" && !("kind" in asset && asset.kind === "file-reference");
}
function getPromptMarkdownAssetDedupKey(asset) {
  return isPromptMarkdownFileReference(asset) ? `file:${path3__default.default.normalize(asset.filePath)}` : `inline:${asset.trim()}`;
}

// src/platform/prompts/build-common-prompt.ts
createPromptMarkdownFileAsset(
  (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('prompt.cjs', document.baseURI).href)),
  "src/platform/prompts/assets/common/base-instructions.md"
);
function buildCommonPrompt(options) {
  return {
    autoYes: options.autoYes,
    forms: options.forms,
    historyReferences: options.historyReferences,
    instructions: options.instructions,
    rules: options.rules,
    sections: options.sections,
    service: options.service,
    title: options.title,
    workspaceSnapshot: options.workspaceSnapshot
  };
}
function normalizePromptFilePath(filePath) {
  return path3__default.default.normalize(filePath).replace(/\\/g, "/").trim();
}
function getNormalizedFileNamePatterns(group) {
  return (group.fileNamePatterns || []).map((pattern) => pattern.trim()).filter(Boolean);
}
function getNormalizedRules(group) {
  return (group.rules || []).filter((asset) => typeof asset === "string" ? Boolean(asset.trim()) : Boolean(asset.filePath.trim()));
}
function createFileMatchCandidates(filePath) {
  const normalized = normalizePromptFilePath(filePath);
  if (!normalized) {
    return [];
  }
  const baseName = path3__default.default.posix.basename(normalized);
  return normalized === baseName ? [normalized] : [normalized, baseName];
}
function compileFileNamePattern(pattern) {
  try {
    return new RegExp(pattern);
  } catch (error) {
    throw new Error(
      `\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 fileNamePatterns \uC815\uADDC\uC2DD\uC785\uB2C8\uB2E4: ${pattern}
${error instanceof Error ? error.message : String(error)}`
    );
  }
}
function normalizePromptTargetFilePaths(filePaths) {
  return filePaths.map(normalizePromptFilePath).filter(Boolean);
}
function matchesPromptRuleGroup(group, targetFilePaths) {
  const normalizedPatterns = getNormalizedFileNamePatterns(group);
  if (normalizedPatterns.length === 0) {
    return true;
  }
  if (targetFilePaths.length === 0) {
    return false;
  }
  return normalizedPatterns.some((pattern) => {
    const regex = compileFileNamePattern(pattern);
    return targetFilePaths.some(
      (filePath) => createFileMatchCandidates(filePath).some((candidate) => regex.test(candidate))
    );
  });
}
function resolvePromptRules(ruleAssets, targetFilePaths = []) {
  if (!ruleAssets || ruleAssets.length === 0) {
    return void 0;
  }
  const normalizedTargetFilePaths = normalizePromptTargetFilePaths(targetFilePaths);
  const resolvedRules = [];
  const seenRules = /* @__PURE__ */ new Set();
  for (const asset of ruleAssets) {
    const nextRules = !isPromptRuleGroupAsset(asset) ? [asset] : matchesPromptRuleGroup(asset, normalizedTargetFilePaths) ? getNormalizedRules(asset) : [];
    for (const rule of nextRules) {
      const dedupeKey = getPromptMarkdownAssetDedupKey(rule);
      if (seenRules.has(dedupeKey)) {
        continue;
      }
      seenRules.add(dedupeKey);
      resolvedRules.push(rule);
    }
  }
  return resolvedRules.length > 0 ? resolvedRules : void 0;
}

// src/features/gen-storybook/application/prompt.ts
function formatExistingStoryContent(content) {
  if (!content.trim()) {
    return "(\uC5C6\uC74C)";
  }
  return ["```tsx", safeExcerpt(content, 4e4), "```"].join("\n");
}
function buildGenStorybookPrompt(options) {
  const normalizedSourceFilePath = path3__default.default.normalize(options.sourceFilePath);
  const normalizedStoryFilePath = path3__default.default.normalize(options.storyFilePath);
  return buildCommonPrompt({
    autoYes: options.autoYes,
    forms: options.promptAssets?.forms,
    historyReferences: options.historyReferences,
    instructions: options.promptAssets?.instructions,
    rules: resolvePromptRules(options.promptAssets?.rules, options.targetFilePaths),
    sections: [
      {
        heading: "\uC791\uC5C5 \uC785\uB825\uAC12",
        markdown: [
          `- \uC6D0\uBCF8 \uC785\uB825\uAC12: ${options.sourceAddress}`,
          `- \uB300\uC0C1 \uCEF4\uD3EC\uB10C\uD2B8 \uD30C\uC77C: ${normalizedSourceFilePath}`,
          `- \uC0DD\uC131 \uB300\uC0C1 story \uD30C\uC77C: ${normalizedStoryFilePath}`,
          `- \uAE30\uC874 story \uD30C\uC77C \uC874\uC7AC \uC5EC\uBD80: ${options.storyFileExists ? "\uC608" : "\uC544\uB2C8\uC624"}`
        ].join("\n")
      },
      {
        heading: "\uB300\uC0C1 \uCEF4\uD3EC\uB10C\uD2B8 \uD30C\uC77C \uB0B4\uC6A9",
        markdown: ["```tsx", safeExcerpt(options.sourceContent, 6e4), "```"].join("\n")
      },
      {
        heading: "\uAE30\uC874 story \uD30C\uC77C \uB0B4\uC6A9",
        markdown: formatExistingStoryContent(options.existingStoryContent)
      }
    ],
    service: options.service,
    title: "Ju-hong-e Gen Storybook",
    workspaceSnapshot: options.workspaceSnapshot
  });
}

exports.buildGenStorybookPrompt = buildGenStorybookPrompt;
