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

// src/platform/core/string-helpers.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 = 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"
  };
}

// 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
  };
}
var PLANNER_RESULT_EXCERPT_LENGTH = 2e3;
function createFocusedTalkToFigmaPromptContext() {
  return {
    workspaceSnapshot: {
      available: false,
      branch: "",
      diffNameStatus: "",
      diffStat: "",
      gitRoot: "",
      note: "",
      recentCommits: [],
      statusLines: []
    }
  };
}
function formatTalkToFigmaRequestMarkdown(request, portHealth) {
  return [
    `- port: ${request.port}`,
    `- channelName: ${request.channelName}`,
    `- portHealth: ${portHealth.ok ? "ok" : "fail"}`,
    `- portHealthDetail: ${portHealth.detail}`,
    "",
    "### \uC0AC\uC6A9\uC790 \uC694\uCCAD",
    request.prompt
  ].join("\n");
}
function formatToolCatalogMarkdown(tools) {
  return tools.map(
    (tool) => [
      `### ${tool.name}`,
      tool.description ? `- description: ${tool.description}` : "- description: (\uC5C6\uC74C)",
      `- inputSchema: ${JSON.stringify(tool.inputSchema || {}, null, 2)}`
    ].join("\n")
  ).join("\n\n");
}
function formatExecutionHistoryMarkdown(executions) {
  if (executions.length === 0) {
    return "- \uC544\uC9C1 \uC2E4\uD589\uD55C \uB3C4\uAD6C\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.";
  }
  return executions.slice(-8).map(
    (execution) => [
      `### Step ${execution.step} - ${execution.toolName}`,
      `- origin: ${execution.origin}`,
      `- ok: ${execution.ok}`,
      `- arguments: ${JSON.stringify(execution.arguments, null, 2)}`,
      "",
      "[\uACB0\uACFC]",
      safeExcerpt(execution.resultText, PLANNER_RESULT_EXCERPT_LENGTH)
    ].join("\n")
  ).join("\n\n");
}
function formatPreviousPlannerResponseMarkdown(previousResponse) {
  if (!previousResponse) {
    return "- \uC774\uC804 \uD30C\uC2F1 \uC2E4\uD328 \uC751\uB2F5\uC740 \uC5C6\uC2B5\uB2C8\uB2E4.";
  }
  return [
    "- \uC9C1\uC804 \uC751\uB2F5\uC774 JSON \uACC4\uC57D\uC744 \uC9C0\uD0A4\uC9C0 \uC54A\uC544 \uC7AC\uC2DC\uB3C4 \uC911\uC774\uB2E4.",
    "",
    "[\uC9C1\uC804 \uC6D0\uBCF8 \uC751\uB2F5]",
    safeExcerpt(previousResponse, PLANNER_RESULT_EXCERPT_LENGTH)
  ].join("\n");
}
function formatPlannerStateMarkdown(plannerStep) {
  return `- plannerStep: ${plannerStep}
- \uB2E4\uC74C \uC751\uB2F5\uC740 JSON object 1\uAC1C\uB9CC \uBC18\uD658\uD574\uC57C \uD55C\uB2E4.`;
}
function buildTalkToFigmaPrompt(options) {
  const focusedPromptContext = createFocusedTalkToFigmaPromptContext();
  return buildCommonPrompt({
    autoYes: options.autoYes,
    forms: options.promptAssets?.forms,
    instructions: options.promptAssets?.instructions,
    sections: [
      {
        heading: "TalkToFigma \uC2E4\uD589 \uC785\uB825",
        markdown: formatTalkToFigmaRequestMarkdown(options.request, options.portHealth)
      },
      {
        heading: "\uD50C\uB798\uB108 \uC0C1\uD0DC",
        markdown: formatPlannerStateMarkdown(options.plannerStep)
      },
      {
        heading: "\uC0AC\uC6A9 \uAC00\uB2A5\uD55C TalkToFigma \uB3C4\uAD6C",
        markdown: formatToolCatalogMarkdown(options.availableTools)
      },
      {
        heading: "\uC774\uBBF8 \uC2E4\uD589\uB41C TalkToFigma \uB3C4\uAD6C",
        markdown: formatExecutionHistoryMarkdown(options.executions)
      },
      {
        heading: "\uC9C1\uC804 JSON \uD30C\uC2F1 \uC2E4\uD328 \uC751\uB2F5",
        markdown: formatPreviousPlannerResponseMarkdown(options.previousInvalidResponse)
      }
    ],
    service: options.service,
    title: "Ju-hong-e Talk To Figma Planner",
    workspaceSnapshot: focusedPromptContext.workspaceSnapshot
  });
}

export { buildTalkToFigmaPrompt };
