import a from './index5.mjs';
import { getContextPersistence } from './persistence.mjs';
import { i18n } from './index2.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:fs';
import 'better-sqlite3';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'node:process';
import 'node:url';

function parseSlashCommand(input) {
  const trimmed = input.trim();
  if (!trimmed.startsWith("/")) {
    return null;
  }
  const parts = trimmed.slice(1).split(/\s+/);
  const command = parts[0].toLowerCase();
  const args = parts.slice(1);
  return { command, args };
}
function getSlashCommands() {
  return [
    {
      name: "status",
      aliases: ["s"],
      description: "Show Brain Dashboard with health score",
      descriptionZh: "\u663E\u793A Brain \u4EEA\u8868\u677F\u548C\u5065\u5EB7\u8BC4\u5206",
      category: "brain",
      handler: async () => {
        const { statusCommand } = await import('./status.mjs');
        await statusCommand({ compact: false });
      }
    },
    {
      name: "health",
      aliases: ["h"],
      description: "Run comprehensive health check",
      descriptionZh: "\u8FD0\u884C\u5168\u9762\u5065\u5EB7\u68C0\u67E5",
      category: "brain",
      handler: async () => {
        const { runHealthCheck } = await import('./index.mjs');
        const report = await runHealthCheck();
        console.log(a.cyan.bold("\n\u{1F3E5} Health Check Results\n"));
        console.log(`${a.gray("Overall Score:")} ${a.green.bold(`${report.totalScore}/100`)}`);
        console.log(`${a.gray("Grade:")} ${a.green.bold(report.grade)}`);
        if (report.recommendations.length > 0) {
          console.log(a.yellow.bold("\n\u{1F4A1} Recommendations:\n"));
          report.recommendations.forEach((rec, i) => {
            console.log(`${a.yellow(`${i + 1}.`)} ${rec.description}`);
            if (rec.command) {
              console.log(`   ${a.gray("\u2192")} ${a.cyan(rec.command)}`);
            }
          });
        }
        console.log();
      }
    },
    {
      name: "search",
      aliases: ["find", "query"],
      description: "Search contexts using FTS5 full-text search",
      descriptionZh: "\u4F7F\u7528 FTS5 \u5168\u6587\u641C\u7D22\u4E0A\u4E0B\u6587",
      category: "context",
      handler: async (args) => {
        if (args.length === 0) {
          console.log(a.yellow("Usage: /search <query>"));
          console.log(a.gray('Example: /search "authentication logic"'));
          return;
        }
        const query = args.join(" ");
        const persistence = getContextPersistence();
        const results = await persistence.searchContexts(query, { limit: 10 });
        if (results.length === 0) {
          console.log(a.yellow(`No results found for: ${query}`));
          return;
        }
        console.log(a.cyan.bold(`
\u{1F50D} Search Results (${results.length})
`));
        results.forEach((result, i) => {
          console.log(a.white.bold(`${i + 1}. ${result.id}`));
          console.log(`   ${a.gray("Rank:")} ${a.yellow(result.rank.toFixed(2))}`);
          console.log(`   ${a.gray("Tokens:")} ${result.originalTokens} \u2192 ${result.compressedTokens}`);
          console.log(`   ${a.gray("Algorithm:")} ${result.algorithm}`);
          if (result.snippet) {
            console.log(`   ${a.gray("Snippet:")} ${a.dim(result.snippet)}`);
          }
          console.log();
        });
      }
    },
    {
      name: "compress",
      aliases: ["stats", "metrics"],
      description: "Show compression statistics and metrics",
      descriptionZh: "\u663E\u793A\u538B\u7F29\u7EDF\u8BA1\u548C\u6307\u6807",
      category: "context",
      handler: async () => {
        const persistence = getContextPersistence();
        const stats = persistence.getCompressionMetricsStats();
        const { displayCompressionStats } = await import('./metrics-display.mjs');
        displayCompressionStats(stats);
      }
    },
    {
      name: "tasks",
      aliases: ["task", "t"],
      description: "Open task manager (Brain system)",
      descriptionZh: "\u6253\u5F00\u4EFB\u52A1\u7BA1\u7406\u5668\uFF08Brain \u7CFB\u7EDF\uFF09",
      category: "brain",
      handler: async () => {
        console.log(a.cyan.bold("\n\u{1F4CB} Task Manager\n"));
        console.log(a.yellow("Task management is integrated with Brain system."));
        console.log(a.gray("Use: ccjk status --tasks to view active tasks"));
        console.log();
      }
    },
    {
      name: "backup",
      aliases: ["save"],
      description: "Create configuration backup",
      descriptionZh: "\u521B\u5EFA\u914D\u7F6E\u5907\u4EFD",
      category: "system",
      handler: async () => {
        const { backupExistingConfig } = await import('./config.mjs').then(function (n) { return n.k; });
        const backupPath = backupExistingConfig();
        if (backupPath) {
          console.log(a.green(`\u2705 Backup created: ${backupPath}`));
        } else {
          console.log(a.yellow("\u26A0\uFE0F  No configuration to backup"));
        }
      }
    },
    {
      name: "optimize",
      aliases: ["vacuum", "cleanup"],
      description: "Run VACUUM + checkpoint on context database",
      descriptionZh: "\u5BF9\u4E0A\u4E0B\u6587\u6570\u636E\u5E93\u8FD0\u884C VACUUM + checkpoint",
      category: "context",
      handler: async () => {
        console.log(a.cyan("\u{1F5DC}\uFE0F  Optimizing context database..."));
        const persistence = getContextPersistence();
        persistence.vacuum();
        console.log(a.green("\u2705 Database optimized (VACUUM completed)"));
      }
    },
    {
      name: "help",
      aliases: ["?", "commands"],
      description: "Show all CCJK slash commands",
      descriptionZh: "\u663E\u793A\u6240\u6709 CCJK \u659C\u6760\u547D\u4EE4",
      category: "system",
      handler: async () => {
        displaySlashCommandsHelp();
      }
    }
  ];
}
async function executeSlashCommand(input) {
  const parsed = parseSlashCommand(input);
  if (!parsed) {
    return false;
  }
  const commands = getSlashCommands();
  const command = commands.find(
    (cmd) => cmd.name === parsed.command || cmd.aliases?.includes(parsed.command)
  );
  if (!command) {
    console.log(a.yellow(`Unknown command: /${parsed.command}`));
    console.log(a.gray("Type /help to see all available commands"));
    return true;
  }
  try {
    await command.handler(parsed.args);
    return true;
  } catch (error) {
    console.error(a.red(`Error executing /${parsed.command}:`), error);
    return true;
  }
}
function displaySlashCommandsHelp() {
  const isZh = i18n.language === "zh-CN";
  const commands = getSlashCommands();
  console.log(a.cyan.bold("\n\u{1F4A1} CCJK Slash Commands\n"));
  const categories = {
    brain: { title: isZh ? "\u{1F9E0} Brain \u7CFB\u7EDF" : "\u{1F9E0} Brain System", commands: [] },
    context: { title: isZh ? "\u{1F4E6} \u4E0A\u4E0B\u6587\u7BA1\u7406" : "\u{1F4E6} Context Management", commands: [] },
    system: { title: isZh ? "\u2699\uFE0F  \u7CFB\u7EDF\u5DE5\u5177" : "\u2699\uFE0F  System Tools", commands: [] }
  };
  commands.forEach((cmd) => {
    categories[cmd.category].commands.push(cmd);
  });
  Object.values(categories).forEach((category) => {
    if (category.commands.length === 0)
      return;
    console.log(a.white.bold(category.title));
    category.commands.forEach((cmd) => {
      const aliases = cmd.aliases ? a.gray(` (${cmd.aliases.map((a) => `/${a}`).join(", ")})`) : "";
      const desc = isZh ? cmd.descriptionZh : cmd.description;
      console.log(`  ${a.green(`/${cmd.name}`)}${aliases}`);
      console.log(`    ${a.gray(desc)}`);
    });
    console.log();
  });
  console.log(a.gray("Tip: Type /help or /? to see this message again\n"));
}

export { displaySlashCommandsHelp, executeSlashCommand, getSlashCommands, parseSlashCommand };
