import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';

// src/features/gen-html/application/prompt.ts
var PACKAGE_JSON_FILE_NAME = "package.json";
function findPackageRoot(moduleFilePath) {
  let currentDirectoryPath = path.dirname(moduleFilePath);
  while (!fs.existsSync(path.join(currentDirectoryPath, PACKAGE_JSON_FILE_NAME))) {
    const parentDirectoryPath = path.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 = fileURLToPath(importMetaUrl);
  const packageRoot = findPackageRoot(moduleFilePath);
  return path.normalize(path.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.normalize(asset.filePath)}` : `inline:${asset.trim()}`;
}

// src/platform/prompts/build-common-prompt.ts
createPromptMarkdownFileAsset(
  import.meta.url,
  "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.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.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-html/application/prompt.ts
function formatGenHtmlLocalServerDependencyMarkdown(localServerDependencies) {
  return Object.entries(localServerDependencies).map(([name, version]) => `- ${name}: ${version}`).join("\n") || "- (\uC5C6\uC74C)";
}
function buildGenHtmlFigmaLookupHintMarkdown(references) {
  const referenceLines = references.flatMap((reference, index) => {
    const lines = [
      `### \uCC38\uC870 ${index + 1}`,
      `- \uC124\uBA85: ${reference.description || "(\uC5C6\uC74C)"}`,
      `- \uC6D0\uBCF8 \uC785\uB825: ${reference.figmaAddress}`,
      reference.figmaSource.fileKey ? `- Figma file key: ${reference.figmaSource.fileKey}` : "- Figma file key: (\uCD94\uCD9C \uC2E4\uD328)",
      reference.figmaSource.branchKey ? `- Figma branch key: ${reference.figmaSource.branchKey}` : "",
      reference.figmaSource.resolvedFileKey ? `- MCP\uC6A9 resolved file key: ${reference.figmaSource.resolvedFileKey}` : "",
      reference.figmaSource.nodeId ? `- \uC6D0\uBCF8 node id: ${reference.figmaSource.nodeId}` : "- \uC6D0\uBCF8 node id: (\uCD94\uCD9C \uC2E4\uD328)",
      reference.figmaSource.normalizedNodeId ? `- \uC6B0\uC120 \uC0AC\uC6A9\uD560 node id: ${reference.figmaSource.normalizedNodeId}` : "- \uC6B0\uC120 \uC0AC\uC6A9\uD560 node id: (\uCD94\uCD9C \uC2E4\uD328)"
    ];
    if (reference.figmaSource.parseNotes.length > 0) {
      lines.push(...reference.figmaSource.parseNotes.map((note) => `- parseNote: ${note}`));
    }
    return lines.filter(Boolean);
  });
  return [
    ...referenceLines,
    "",
    "### MCP \uC870\uD68C \uC6D0\uCE59",
    "1. \uAC01 Figma MCP \uD638\uCD9C\uC758 `nodeId` \uC778\uC790\uC5D0\uB294 URL \uC804\uCCB4\uAC00 \uC544\uB2C8\uB77C \uD574\uB2F9 \uCC38\uC870\uC5D0\uC11C \uCD94\uCD9C\uD55C node id\uB9CC \uC0AC\uC6A9\uD55C\uB2E4.",
    "2. \uC6B0\uC120 `figma/get_metadata` \uB85C \uAD6C\uC870\uB97C \uD655\uC778\uD55C \uB4A4 `figma/get_design_context` \uB97C \uC2DC\uB3C4\uD55C\uB2E4.",
    "3. `get_design_context` \uAC00 timeout \uB418\uBA74 `figma/get_screenshot`, `figma/get_variable_defs` \uB85C \uD544\uC694\uD55C \uC815\uBCF4\uB97C \uBCF4\uAC15\uD55C\uB2E4.",
    "4. \uADF8\uB798\uB3C4 \uBD80\uC871\uD558\uBA74 `TalkToFigma/get_node_info`, `scan_text_nodes`, `scan_nodes_by_types` \uB85C \uAC19\uC740 node id\uB97C \uC9C1\uC811 \uC77D\uC5B4 \uAD6C\uC870\uB97C \uBCF5\uC6D0\uD55C\uB2E4.",
    "5. URL \uC804\uCCB4\uB97C `nodeId` \uC790\uB9AC\uC5D0 \uB118\uACA8 schema mismatch\uB97C \uB9CC\uB4E4\uC9C0 \uC54A\uB294\uB2E4."
  ].filter(Boolean).join("\n");
}
function buildGenHtmlExecutionInputMarkdown(options) {
  return [
    `- \uCEF4\uD3EC\uB10C\uD2B8\uBA85: ${options.componentName}`,
    `- \uCD9C\uB825 \uB514\uB809\uD130\uB9AC: ${path.normalize(options.outputPath)}`,
    `- Storybook title prefix: ${options.storyTitlePrefix}`,
    "",
    "### Figma \uCC38\uC870 \uBAA9\uB85D",
    ...options.references.map(
      (reference, index) => [
        `${index + 1}. ${reference.description || "(\uC124\uBA85 \uC5C6\uC74C)"}`,
        `- \uC8FC\uC18C: ${reference.figmaAddress}`,
        reference.figmaSource.normalizedNodeId ? `- \uCD94\uCD9C\uB41C Figma node id: ${reference.figmaSource.normalizedNodeId}` : "- \uCD94\uCD9C\uB41C Figma node id: (\uCD94\uCD9C \uC2E4\uD328)"
      ].join("\n")
    ),
    "",
    "### \uB85C\uCEEC \uD504\uB9AC\uBDF0 \uC11C\uBC84 \uC758\uC874\uC131",
    formatGenHtmlLocalServerDependencyMarkdown(options.localServerDependencies)
  ].join("\n");
}
function buildGenHtmlPrompt(options) {
  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: buildGenHtmlExecutionInputMarkdown({
          componentName: options.componentName,
          localServerDependencies: options.localServerDependencies,
          outputPath: options.outputPath,
          references: options.references,
          storyTitlePrefix: options.storyTitlePrefix
        })
      },
      {
        heading: "Figma \uC870\uD68C \uD78C\uD2B8",
        markdown: buildGenHtmlFigmaLookupHintMarkdown(options.references)
      }
    ],
    service: options.service,
    title: "Ju-hong-e Gen HTML",
    workspaceSnapshot: options.workspaceSnapshot
  });
}

export { buildGenHtmlPrompt };
