import { formatForInkCli } from "./utils/format-output.js";
import { createSendMessageMarker } from "../services/index.js";
const promptCommands = [
  {
    name: "sysprompt",
    description: "Display the current system prompt",
    usage: "/sysprompt",
    category: "Prompt Management",
    handler: async (_args, agent, _ctx) => {
      try {
        const systemPrompt = await agent.getSystemPrompt();
        const styledOutput = {
          styledType: "sysprompt",
          styledData: { content: systemPrompt },
          fallbackText: `System Prompt:
${systemPrompt}`
        };
        return styledOutput;
      } catch (error) {
        const errorMsg = `Failed to get system prompt: ${error instanceof Error ? error.message : String(error)}`;
        agent.logger.error(errorMsg);
        return formatForInkCli(`\u274C ${errorMsg}`);
      }
    }
  },
  {
    name: "prompts",
    description: "Browse, add, and delete prompts",
    usage: "/prompts",
    category: "Prompt Management",
    handler: async (_args, agent, _ctx) => {
      try {
        const prompts = await agent.listPrompts();
        const promptNames = Object.keys(prompts || {});
        if (promptNames.length === 0) {
          const output2 = "\n\u26A0\uFE0F  No prompts available";
          return formatForInkCli(output2);
        }
        const outputLines = ["\n\u{1F4DD} Available Prompts:\n"];
        const mcpPrompts = [];
        const configPrompts = [];
        const customPrompts = [];
        for (const [name, info] of Object.entries(prompts)) {
          if (info.source === "mcp") {
            mcpPrompts.push(name);
          } else if (info.source === "config") {
            configPrompts.push(name);
          } else if (info.source === "custom") {
            customPrompts.push(name);
          }
        }
        if (mcpPrompts.length > 0) {
          outputLines.push("\u{1F517} MCP Prompts:");
          mcpPrompts.forEach((name) => {
            const info = prompts[name];
            if (info) {
              const displayName = info.displayName || name;
              const title = info.title && info.title !== displayName ? ` (${info.title})` : "";
              const desc = info.description ? ` - ${info.description}` : "";
              const args = info.arguments && info.arguments.length > 0 ? ` [args: ${info.arguments.map((a) => `${a.name}${a.required ? "*" : ""}`).join(", ")}]` : "";
              outputLines.push(`  ${displayName}${title}${desc}${args}`);
            }
          });
          outputLines.push("");
        }
        if (configPrompts.length > 0) {
          outputLines.push("\u{1F4CB} Config Prompts:");
          configPrompts.forEach((name) => {
            const info = prompts[name];
            if (info) {
              const displayName = info.displayName || name;
              const title = info.title && info.title !== displayName ? ` (${info.title})` : "";
              const desc = info.description ? ` - ${info.description}` : "";
              outputLines.push(`  ${displayName}${title}${desc}`);
            }
          });
          outputLines.push("");
        }
        if (customPrompts.length > 0) {
          outputLines.push("\u2728 Custom Prompts:");
          customPrompts.forEach((name) => {
            const info = prompts[name];
            if (info) {
              const displayName = info.displayName || name;
              const title = info.title && info.title !== displayName ? ` (${info.title})` : "";
              const desc = info.description ? ` - ${info.description}` : "";
              outputLines.push(`  ${displayName}${title}${desc}`);
            }
          });
          outputLines.push("");
        }
        outputLines.push(`Total: ${promptNames.length} prompts`);
        const output = outputLines.join("\n");
        return formatForInkCli(output);
      } catch (error) {
        const errorMsg = `Error listing prompts: ${error instanceof Error ? error.message : String(error)}`;
        return formatForInkCli(`\u274C ${errorMsg}`);
      }
    }
  }
  // Note: /use command removed - use /<prompt-name> directly instead
  // Prompts are automatically registered as slash commands (see getDynamicPromptCommands)
];
function createPromptCommand(promptInfo) {
  const commandName = promptInfo.commandName || promptInfo.displayName || promptInfo.name;
  const internalName = promptInfo.name;
  const baseName = promptInfo.displayName || promptInfo.name;
  return {
    name: commandName,
    description: promptInfo.description || `Execute ${baseName} prompt`,
    usage: `/${commandName} [context]`,
    category: "Dynamic Prompts",
    handler: async (args, agent, _ctx) => {
      try {
        const { argMap, context: contextString } = splitPromptArguments(args);
        const resolveOptions = {};
        if (Object.keys(argMap).length > 0) {
          resolveOptions.args = argMap;
        }
        if (contextString) {
          resolveOptions.context = contextString;
        }
        const result = await agent.resolvePrompt(internalName, resolveOptions);
        let finalText = result.text;
        if (result.resources.length > 0) {
          const resourceRefs = result.resources.map((uri) => `@<${uri}>`).join(" ");
          finalText = finalText ? `${finalText}

${resourceRefs}` : resourceRefs;
        }
        if (finalText.trim()) {
          return createSendMessageMarker(finalText.trim());
        }
        const warningMsg = `\u26A0\uFE0F  Prompt '${commandName}' returned no content`;
        return formatForInkCli(warningMsg);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        agent.logger.error(
          `Failed to execute prompt command '${commandName}': ${errorMessage}`
        );
        const errorMsg = `\u274C Error executing prompt '${commandName}': ${errorMessage}`;
        return formatForInkCli(errorMsg);
      }
    }
  };
}
async function getDynamicPromptCommands(agent) {
  try {
    const prompts = await agent.listPrompts();
    const promptEntries = Object.entries(prompts).filter(
      ([, info]) => info.userInvocable !== false
    );
    return promptEntries.map(([, info]) => createPromptCommand(info));
  } catch (error) {
    agent.logger.error(
      `Failed to get dynamic prompt commands: ${error instanceof Error ? error.message : String(error)}`
    );
    return [];
  }
}
function splitPromptArguments(args) {
  const map = {};
  const contextParts = [];
  for (const arg of args) {
    const equalsIndex = arg.indexOf("=");
    if (equalsIndex > 0) {
      const key = arg.slice(0, equalsIndex).trim();
      const value = arg.slice(equalsIndex + 1);
      if (key.length > 0) {
        map[key] = value;
      }
    } else if (arg.trim().length > 0) {
      contextParts.push(arg);
    }
  }
  const context = contextParts.length > 0 ? contextParts.join(" ") : void 0;
  return { argMap: map, context };
}
export {
  getDynamicPromptCommands,
  promptCommands
};
