/**
 * Search command.
 */

import { Command } from 'commander';
import { EmdashClient } from '../client.js';
import { getServerManager } from '../server-manager.js';
import { style } from '../design.js';

export const searchCommand = new Command('search')
  .description('Search the codebase')
  .argument('<query>', 'Search query')
  .option('-t, --type <type>', 'Search type (semantic, text, grep)', 'semantic')
  .option('-l, --limit <n>', 'Maximum results', '20')
  .action(async (query: string, options: { type: string; limit: string }) => {
    const manager = getServerManager();
    const url = await manager.ensureServer();
    const client = new EmdashClient(url);

    try {
      const result = await client.search(
        query,
        options.type,
        parseInt(options.limit, 10)
      );

      console.log(`Search Results (${result.total} found):`);
      console.log();

      for (const item of result.results) {
        console.log(`  ${style.primary(item.name)} ${style.dim(`(${item.type})`)}`);
        console.log(`    ${style.muted(item.file)}${item.line ? `:${item.line}` : ''}`);
        if (item.score !== undefined) {
          console.log(`    Score: ${item.score.toFixed(3)}`);
        }
        if (item.content) {
          const preview = item.content.slice(0, 100).replace(/\n/g, ' ');
          console.log(`    ${style.dim(preview)}${item.content.length > 100 ? '...' : ''}`);
        }
        console.log();
      }
    } catch (error) {
      console.error(style.error('Search failed:'), (error as Error).message);
      process.exit(1);
    }
  });
