/**
 * Indexing commands.
 */

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

export const indexCommand = new Command('index')
  .description('Code indexing commands')
  .addCommand(
    new Command('status')
      .description('Get indexing status for a repository')
      .option('-p, --path <path>', 'Repository path', process.cwd())
      .action(async (options: { path: string }) => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const status = await client.indexStatus(options.path);
          console.log('Index Status:');
          console.log(`  Status: ${status.status}`);
          console.log(`  Files Indexed: ${status.files_indexed}`);
          console.log(`  Total Files: ${status.total_files}`);
          if (status.last_updated) {
            console.log(`  Last Updated: ${status.last_updated}`);
          }
        } catch (error) {
          console.error(style.error('Failed to get status:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('start')
      .description('Start indexing a repository')
      .option('-p, --path <path>', 'Repository path', process.cwd())
      .option('-i, --incremental', 'Only index changed files')
      .action(async (options: { path: string; incremental?: boolean }) => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);
        const renderer = new SSERenderer(true);

        try {
          console.log(`Indexing ${options.path}...`);
          const stream = client.indexStartStream(options.path, options.incremental ?? false);
          await renderer.renderStream(stream);
          console.log(style.success('Indexing complete'));
        } catch (error) {
          console.error(style.error('Indexing failed:'), (error as Error).message);
          process.exit(1);
        }
      })
  );
