import chalk from "chalk";
import { Command } from "commander";
import { del, get, post } from "./api.js";

/**
 * Add duplicate detection and indexing commands to the CLI
 */
export function addIndexingCommands(program: Command) {
  // Duplicate detection and indexing commands
  program
    .command("duplicates:scan")
    .description("Scan for duplicate files (uses database if indexed)")
    .option("--reset", "Reset existing duplicate groups")
    .action(async (opts) => {
      console.log(chalk.blue("🔍 Scanning for duplicates..."));
      const result = await post("/maintenance/duplicates/scan", {
        resetExisting: opts.reset || false,
      });
      console.log(chalk.green("✅ Scan complete"));
      console.log(result);
    });

  program
    .command("duplicates:list")
    .description("List duplicate file groups")
    .option("--status <status>", "Filter by status (pending/reviewed/purged)")
    .option("--dataset <dataset>", "Filter by dataset")
    .action(async (opts) => {
      const params: any = {};
      if (opts.status) params.status = opts.status;
      if (opts.dataset) params.dataset = opts.dataset;

      const duplicates = await get("/maintenance/duplicates", params);
      if (Array.isArray(duplicates) && duplicates.length > 0) {
        console.log(
          chalk.yellow(`Found ${duplicates.length} duplicate groups:\n`)
        );
        duplicates.forEach((dup: any) => {
          console.log(
            `${chalk.cyan(`[${dup.dataset}]`)} ${dup.files.length} files, ${(dup.size / 1024 / 1024).toFixed(2)} MB`
          );
          console.log(`  Hash: ${dup.hash.substring(0, 16)}...`);
          dup.files.forEach((file: string) => console.log(`  - ${file}`));
          console.log();
        });
      } else {
        console.log(chalk.green("✨ No duplicates found"));
      }
    });

  program
    .command("index:destination")
    .description("Index destination files for fast duplicate detection")
    .requiredOption("--dataset <dataset>", "Dataset name")
    .requiredOption("--destination <destination>", "Destination directory path")
    .option("--reindex", "Clear and rebuild the index")
    .option("--batch-size <size>", "Number of files to process at once", "100")
    .action(async (opts) => {
      console.log(
        chalk.blue(
          `📁 Indexing ${opts.dataset} destination: ${opts.destination}`
        )
      );

      const result = await post("/maintenance/index/destination", {
        dataset: opts.dataset,
        destination: opts.destination,
        reindex: opts.reindex || false,
        batchSize: parseInt(opts.batchSize),
      });

      console.log(
        chalk.green(
          `✅ Indexed: ${result.indexed}, Skipped: ${result.skipped}, Errors: ${result.errors}`
        )
      );
    });

  program
    .command("index:stats")
    .description("Get duplicate statistics from indexed files")
    .option("--dataset <dataset>", "Filter by dataset")
    .action(async (opts) => {
      const params = opts.dataset ? { dataset: opts.dataset } : undefined;
      const stats = await get("/maintenance/index/stats", params);

      console.log(chalk.blue(`📊 Duplicate Statistics`));
      console.log(
        `Total duplicate groups: ${chalk.yellow(stats.totalDuplicates)}`
      );

      if (stats.duplicatesByDataset.length > 0) {
        console.log(chalk.cyan("\nDuplicate Groups:"));
        stats.duplicatesByDataset
          .slice(0, 10)
          .forEach((dup: any, idx: number) => {
            console.log(
              `\n${idx + 1}. ${chalk.cyan(`[${dup.dataset}]`)} ${dup.file_count} files, ${(dup.file_size / 1024 / 1024).toFixed(2)} MB`
            );
            console.log(`   Hash: ${dup.hash.substring(0, 16)}...`);
            dup.files.forEach((file: string) => console.log(`   - ${file}`));
          });

        if (stats.duplicatesByDataset.length > 10) {
          console.log(
            chalk.dim(
              `\n... and ${stats.duplicatesByDataset.length - 10} more groups`
            )
          );
        }
      }
    });

  program
    .command("index:count")
    .description("Get count of indexed destination files")
    .requiredOption("--dataset <dataset>", "Dataset name")
    .option("--destination <destination>", "Filter by destination path")
    .action(async (opts) => {
      const params: any = { dataset: opts.dataset };
      if (opts.destination) params.destination = opts.destination;

      const result = await get("/maintenance/index/count", params);
      console.log(
        chalk.blue(
          `📈 Indexed files for ${opts.dataset}: ${chalk.yellow(result.count)}`
        )
      );
    });

  program
    .command("index:clear")
    .description("Clear destination file index")
    .requiredOption("--dataset <dataset>", "Dataset name")
    .option("--destination <destination>", "Filter by destination path")
    .action(async (opts) => {
      const params = opts.destination
        ? { destination: opts.destination }
        : undefined;
      const result = await del(`/maintenance/index/${opts.dataset}`, params);
      console.log(chalk.green(`🗑️  Cleared ${result.cleared} index entries`));
    });
}
