'use strict';

var path = require('path');
var fs = require('fs');
var url = require('url');

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

var path__default = /*#__PURE__*/_interopDefault(path);
var fs__default = /*#__PURE__*/_interopDefault(fs);

// src/features/minify-md/application/prompt.ts
var PACKAGE_JSON_FILE_NAME = "package.json";
function findPackageRoot(moduleFilePath) {
  let currentDirectoryPath = path__default.default.dirname(moduleFilePath);
  while (!fs__default.default.existsSync(path__default.default.join(currentDirectoryPath, PACKAGE_JSON_FILE_NAME))) {
    const parentDirectoryPath = path__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 path__default.default.normalize(path__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:${path__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 path__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 = path__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/minify-md/application/prompt.ts
function createFocusedMdMinifyPromptContext() {
  return {
    workspaceSnapshot: {
      available: false,
      branch: "",
      diffNameStatus: "",
      diffStat: "",
      gitRoot: "",
      note: "",
      recentCommits: [],
      statusLines: []
    }
  };
}
function buildMdMinifyPrompt(options) {
  const focusedPromptContext = createFocusedMdMinifyPromptContext();
  return buildCommonPrompt({
    autoYes: options.autoYes,
    forms: options.promptAssets?.forms,
    historyReferences: options.historyReferences,
    instructions: options.promptAssets?.instructions,
    rules: resolvePromptRules(options.promptAssets?.rules, [options.sourceFilePath, options.targetFilePath, options.targetLogFilePath]),
    sections: [
      {
        heading: "\uC791\uC5C5 \uC785\uB825\uAC12",
        markdown: [
          `- \uC0AC\uC6A9\uC790 \uC785\uB825 \uACBD\uB85C: ${path__default.default.normalize(options.sourcePathInput)}`,
          `- \uC6D0\uBCF8 \uD30C\uC77C: ${path__default.default.normalize(options.sourceFilePath)}`,
          `- \uC800\uC7A5 \uB300\uC0C1 min \uD30C\uC77C: ${path__default.default.normalize(options.targetFilePath)}`,
          `- \uC800\uC7A5 \uB300\uC0C1 log \uD30C\uC77C: ${path__default.default.normalize(options.targetLogFilePath)}`
        ].join("\n")
      },
      {
        heading: "\uC6D0\uBCF8 markdown",
        markdown: options.sourceContent.trim() || "(\uBE48 \uBB38\uC11C)"
      }
    ],
    service: options.service,
    title: "Ju-hong-e Minify Markdown",
    workspaceSnapshot: focusedPromptContext.workspaceSnapshot
  });
}

exports.buildMdMinifyPrompt = buildMdMinifyPrompt;
