import { resolve } from "path";
import { program } from "commander";
import { timestretch } from "./renderer.js";

interface CliOptions {
  output: string;
  transpose: string;
  warpMarkers: string | null;
}

program
  .name("stretchtool")
  .description("Command line utility to timestretch audio")
  .version("1.0.0");

program
  .argument("<inputfile>", "Path to the input audio file")
  .option(
    "-o, --output <path>",
    "Output file path (default: output.wav)",
    "output.wav"
  )
  .option(
    "-t, --transpose <semitones>",
    "Transposition in fractional semitones",
    "0"
  )
  .option(
    "-w, --warp-markers <path>",
    "Path to the warp markers file (lines of <input_time> <output_time>)"
  )
  .action(async (inputPath: string, options: CliOptions) => {
    try {
      const resolvedInputPath = resolve(inputPath);
      const resolvedOutputPath = resolve(options.output);
      const resolvedWarpMarkersPath = options.warpMarkers
        ? resolve(options.warpMarkers)
        : null;

      console.log(`Input file: ${resolvedInputPath}`);
      console.log(`Output file: ${resolvedOutputPath}`);
      if (resolvedWarpMarkersPath) {
        console.log(`Warp markers file: ${resolvedWarpMarkersPath}`);
      }
      console.log(`Transposition: ${options.transpose} st`);

      const startTime = Date.now();

      await timestretch(
        resolvedInputPath,
        resolvedOutputPath,
        parseFloat(options.transpose),
        resolvedWarpMarkersPath
      );

      const duration = ((Date.now() - startTime) / 1000).toFixed(2);
      console.log(`Timestretching completed in ${duration}s`);
    } catch (error) {
      console.error(error);
      process.exit(1);
    }
  });

program.parse();
