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

const program = new Command();

program
  .option("-i, --interactive", "Run in interactive mode")
  .name("watch-finished-cli")
  .description("CLI for Watch Finished Service")
  .version("1.0.0");

// Config commands
program
  .command("config:list")
  .description("List available config files")
  .action(async () => {
    const configs = await get("/config/list");
    console.table(configs);
  });

program
  .command("config:settings")
  .description("Get settings (optionally by key)")
  .option("--key <key>", "Settings key")
  .action(async (opts: { key?: string }) => {
    const settings = await get(
      "/config/settings",
      opts.key ? { key: opts.key } : undefined
    );
    console.log(settings);
  });

program
  .command("config:file")
  .description("Get a config file by name")
  .requiredOption("--name <name>", "Config file name")
  .action(async (opts: { name: string }) => {
    const file = await get(`/config/files/${opts.name}`);
    console.log(file);
  });

// Watcher commands
program
  .command("watcher:start")
  .description("Start the watcher")
  .requiredOption("--watches <watches>", "Comma-separated list of globs")
  .action(async (opts) => {
    const watches = opts.watches.split(",").map((w: string) => w.trim());
    const result = await post("/watcher/start", { watches });
    console.log(result);
  });

program
  .command("watcher:stop")
  .description("Stop the watcher")
  .action(async () => {
    const result = await post("/watcher/stop");
    console.log(result);
  });

program
  .command("watcher:status")
  .description("Get watcher status")
  .action(async () => {
    const status = await get("/watcher/status");
    console.log(status);
  });

// Maintenance commands
program
  .command("maintenance:cleanup")
  .description("Cleanup a file from DB if missing")
  .requiredOption("--file <file>", "File path")
  .requiredOption("--dirs <dirs>", "Comma-separated list of dirs")
  .action(async (opts) => {
    const dirs = opts.dirs.split(",").map((d: string) => d.trim());
    const result = await post("/maintenance/cleanup", {
      file: opts.file,
      dirs
    });
    console.log(result);
  });

program
  .command("maintenance:purge")
  .description("Purge deleted records older than a threshold")
  .requiredOption("--dirs <dirs>", "Comma-separated list of dirs")
  .option("--dayMs <dayMs>", "Milliseconds for age threshold")
  .option("--cleanerMs <cleanerMs>", "Milliseconds for purge interval")
  .action(async (opts) => {
    const dirs = opts.dirs.split(",").map((d: string) => d.trim());
    const result = await post("/maintenance/purge", {
      dirs,
      dayMs: opts.dayMs,
      cleanerMs: opts.cleanerMs
    });
    console.log(result);
  });

program
  .command("maintenance:prune")
  .description("Prune processed files that no longer exist")
  .requiredOption("--dirs <dirs>", "Comma-separated list of dirs")
  .action(async (opts) => {
    const dirs = opts.dirs.split(",").map((d: string) => d.trim());
    const result = await post("/maintenance/prune", { dirs });
    console.log(result);
  });

// Handbrake commands
program
  .command("handbrake:presets")
  .description("List HandBrake presets")
  .action(async () => {
    const presets = await get("/handbrake/presets");
    console.log(presets);
  });

program
  .command("handbrake:process")
  .description("Process a video file with HandBrake")
  .requiredOption("--input <input>", "Input file")
  .requiredOption("--output <output>", "Output file")
  .requiredOption("--preset <preset>", "HandBrake preset")
  .action(async (opts) => {
    const result = await post("/handbrake/process", {
      input: opts.input,
      output: opts.output,
      preset: opts.preset
    });
    console.log(result);
  });

// File CRUD commands
program
  .command("file:get")
  .description("Get a file record")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--file <file>", "Input file path")
  .action(async (opts) => {
    const file = await get(`/files/${opts.dataset}/${opts.file}`);
    console.log(file);
  });

program
  .command("file:set")
  .description("Set (create/update) a file record")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--file <file>", "Input file path")
  .option("--output <output>", "Output file path")
  .option("--status <status>", "File status")
  .option("--date <date>", "Date (ISO string)")
  .action(async (opts) => {
    const payload: any = {};
    if (opts.output) payload.output = opts.output;
    if (opts.status) payload.status = opts.status;
    if (opts.date) payload.date = opts.date;
    const result = await post(`/files/${opts.dataset}/${opts.file}`, payload);
    console.log(result);
  });

program
  .command("file:remove")
  .description("Remove a file record")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--file <file>", "Input file path")
  .option("--soft <soft>", "Soft delete (true/false)", "true")
  .action(async (opts) => {
    const result = await del(`/files/${opts.dataset}/${opts.file}`, {
      soft: opts.soft
    });
    console.log(result);
  });

program
  .command("files:deleted-older-than")
  .description("Get deleted files older than a date")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--isoDate <isoDate>", "ISO date string")

  .action(async (opts) => {
    const files = await get(
      `/files/${opts.dataset}/deleted-older-than/${opts.isoDate}`
    );
    console.table(files);
  });

program
  .name("watch-finished-cli")
  .description("CLI for Watch Finished Service")
  .version("1.0.0");

program.addHelpText(
  "beforeAll",
  `\nWatch Finished CLI\n==================\nInteract with the Watch Finished backend service via the command line.\n\nExamples:\n  $ watch-finished-cli list --dataset movies\n  $ watch-finished-cli file:get --dataset movies --file mymovie.mkv\n  $ watch-finished-cli config:list\n  $ watch-finished-cli watcher:start --watches "/data/movies,/data/tvshows"\n  $ watch-finished-cli handbrake:process --input in.mkv --output out.m4v --preset "Fast 1080p30"\n  $ watch-finished-cli task:list\n  $ watch-finished-cli task:queue:settings:update --batch-size 5 --concurrency 2\n\nFor full command documentation, use --help with any command.\n`
);

program.addHelpText(
  "afterAll",
  `\nFor more information, see the project README or run a command with --help.\n`
);

// Basic hello command
program
  .command("hello")
  .description("Print hello world")
  .action(() => {
    console.log(chalk.green("Hello from the Watch Finished CLI!"));
  });

// List files command
program
  .command("list")
  .description("List files in a dataset")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .option("--status <status>", "File status", "success")
  .action(async (opts) => {
    try {
      const files = await get(`/files/${opts.dataset}/status/${opts.status}`);
      if (Array.isArray(files)) {
        console.table(files);
      } else {
        console.log(files);
      }
    } catch (err) {
      const e = err as any;
      console.error(chalk.red("Error:", e && e.message ? e.message : e));
    }
  });

// Config commands
program
  .command("config:list")
  .description("List available config files")
  .action(async () => {
    const configs = await get("/config/list");
    console.table(configs);
  });

program
  .command("config:settings")
  .description("Get settings (optionally by key)")
  .option("--key <key>", "Settings key")
  .action(async (opts) => {
    const settings = await get(
      "/config/settings",
      opts.key ? { key: opts.key } : undefined
    );
    console.log(settings);
  });

program
  .command("config:file")
  .description("Get a config file by name")
  .requiredOption("--name <name>", "Config file name")
  .action(async (opts) => {
    const file = await get(`/config/files/${opts.name}`);
    console.log(file);
  });

// Watcher commands
program
  .command("watcher:start")
  .description("Start the watcher")
  .requiredOption("--watches <watches>", "Comma-separated list of globs")
  .action(async (opts) => {
    const watches = opts.watches.split(",").map((w: string) => w.trim());
    const result = await post("/watcher/start", { watches });
    console.log(result);
  });

program
  .command("watcher:stop")
  .description("Stop the watcher")
  .action(async () => {
    const result = await post("/watcher/stop");
    console.log(result);
  });

program
  .command("watcher:status")
  .description("Get watcher status")
  .action(async () => {
    const status = await get("/watcher/status");
    console.log(status);
  });

// Maintenance commands
program
  .command("maintenance:cleanup")
  .description("Cleanup a file from DB if missing")
  .requiredOption("--file <file>", "File path")
  .requiredOption("--dirs <dirs>", "Comma-separated list of dirs")
  .action(async (opts) => {
    const dirs = opts.dirs.split(",").map((d: string) => d.trim());
    const result = await post("/maintenance/cleanup", {
      file: opts.file,
      dirs
    });
    console.log(result);
  });

program
  .command("maintenance:purge")
  .description("Purge deleted records older than a threshold")
  .requiredOption("--dirs <dirs>", "Comma-separated list of dirs")
  .option("--dayMs <dayMs>", "Milliseconds for age threshold")
  .option("--cleanerMs <cleanerMs>", "Milliseconds for purge interval")
  .action(async (opts) => {
    const dirs = opts.dirs.split(",").map((d: string) => d.trim());
    const result = await post("/maintenance/purge", {
      dirs,
      dayMs: opts.dayMs,
      cleanerMs: opts.cleanerMs
    });
    console.log(result);
  });

program
  .command("maintenance:prune")
  .description("Prune processed files that no longer exist")
  .requiredOption("--dirs <dirs>", "Comma-separated list of dirs")
  .action(async (opts) => {
    const dirs = opts.dirs.split(",").map((d: string) => d.trim());
    const result = await post("/maintenance/prune", { dirs });
    console.log(result);
  });

// Handbrake commands
program
  .command("handbrake:presets")
  .description("List HandBrake presets")
  .action(async () => {
    const presets = await get("/handbrake/presets");
    console.log(presets);
  });

program
  .command("handbrake:process")
  .description("Process a video file with HandBrake")
  .requiredOption("--input <input>", "Input file")
  .requiredOption("--output <output>", "Output file")
  .requiredOption("--preset <preset>", "HandBrake preset")
  .action(async (opts) => {
    const result = await post("/handbrake/process", {
      input: opts.input,
      output: opts.output,
      preset: opts.preset
    });
    console.log(result);
  });

// File CRUD commands
program
  .command("file:get")
  .description("Get a file record")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--file <file>", "Input file path")
  .action(async (opts) => {
    const file = await get(`/files/${opts.dataset}/${opts.file}`);
    console.log(file);
  });

program
  .command("file:set")
  .description("Set (create/update) a file record")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--file <file>", "Input file path")
  .option("--output <output>", "Output file path")
  .option("--status <status>", "File status")
  .option("--date <date>", "Date (ISO string)")
  .action(async (opts) => {
    const payload: any = {};
    if (opts.output) payload.output = opts.output;
    if (opts.status) payload.status = opts.status;
    if (opts.date) payload.date = opts.date;
    const result = await post(`/files/${opts.dataset}/${opts.file}`, payload);
    console.log(result);
  });

program
  .command("file:remove")
  .description("Remove a file record")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--file <file>", "Input file path")
  .option("--soft <soft>", "Soft delete (true/false)", "true")
  .action(async (opts) => {
    const result = await del(`/files/${opts.dataset}/${opts.file}`, {
      soft: opts.soft
    });
    console.log(result);
  });

program
  .command("files:deleted-older-than")
  .description("Get deleted files older than a date")
  .requiredOption("--dataset <dataset>", "Dataset name")
  .requiredOption("--isoDate <isoDate>", "ISO date string")
  .action(async (opts) => {
    const files = await get(
      `/files/${opts.dataset}/deleted-older-than/${opts.isoDate}`
    );
    console.table(files);
  });

// Task management commands
program
  .command("task:list")
  .description("List all tasks")
  .action(async () => {
    const tasks = await get("/tasks");
    console.table(tasks);
  });

program
  .command("task:get")
  .description("Get a task by ID")
  .requiredOption("--id <id>", "Task ID")
  .action(async (opts) => {
    const task = await get(`/tasks/${opts.id}`);
    console.log(task);
  });

program
  .command("task:delete")
  .description("Delete a task by ID")
  .requiredOption("--id <id>", "Task ID")
  .action(async (opts) => {
    const result = await del(`/tasks/${opts.id}`);
    console.log(result);
  });

program
  .command("task:queue:status")
  .description("Get queue status")
  .action(async () => {
    const status = await get("/tasks/queue/status");
    console.log(status);
  });

program
  .command("task:queue:settings")
  .description("Get queue settings")
  .action(async () => {
    const settings = await get("/tasks/queue/settings");
    console.log(settings);
  });

program
  .command("task:queue:settings:update")
  .description("Update queue settings")
  .option("--batch-size <size>", "Batch size (number)", parseInt)
  .option("--concurrency <count>", "Concurrency limit (number)", parseInt)
  .option(
    "--retry-enabled <enabled>",
    "Enable retries (true/false)",
    (v) => v === "true"
  )
  .option("--max-retries <count>", "Maximum retry attempts (number)", parseInt)
  .option(
    "--retry-delay <ms>",
    "Retry delay in milliseconds (number)",
    parseInt
  )
  .option(
    "--processing-interval <ms>",
    "Processing interval in milliseconds (number)",
    parseInt
  )
  .action(async (opts) => {
    const settings: any = {};
    if (opts.batchSize !== undefined) settings.batchSize = opts.batchSize;
    if (opts.concurrency !== undefined) settings.concurrency = opts.concurrency;
    if (opts.retryEnabled !== undefined)
      settings.retryEnabled = opts.retryEnabled;
    if (opts.maxRetries !== undefined) settings.maxRetries = opts.maxRetries;
    if (opts.retryDelay !== undefined) settings.retryDelay = opts.retryDelay;
    if (opts.processingInterval !== undefined)
      settings.processingInterval = opts.processingInterval;

    const result = await post("/tasks/queue/settings", settings);
    console.log("Queue settings updated:", result);
  });

// Interactive CLI function
async function runInteractive() {
  console.log(chalk.bold.blue("🚀 Watch Finished Interactive CLI"));
  console.log(chalk.gray("Choose a command to execute...\n"));

  while (true) {
    const { category } = await inquirer.prompt([
      {
        type: "list",
        name: "category",
        message: "What would you like to do?",
        choices: [
          { name: "📋 Task Management", value: "tasks" },
          { name: "📁 File Operations", value: "files" },
          { name: "⚙️  Configuration", value: "config" },
          { name: "👀 Watcher Control", value: "watcher" },
          { name: "🧹 Maintenance", value: "maintenance" },
          { name: "🎬 HandBrake", value: "handbrake" },
          { name: "❌ Exit", value: "exit" }
        ]
      }
    ]);

    if (category === "exit") {
      console.log(chalk.green("Goodbye! 👋"));
      process.exit(0);
    }

    await handleCategory(category);
  }
}

async function handleCategory(category: string) {
  switch (category) {
    case "tasks":
      await handleTaskCommands();
      break;
    case "files":
      await handleFileCommands();
      break;
    case "config":
      await handleConfigCommands();
      break;
    case "watcher":
      await handleWatcherCommands();
      break;
    case "maintenance":
      await handleMaintenanceCommands();
      break;
    case "handbrake":
      await handleHandbrakeCommands();
      break;
  }
}

async function handleTaskCommands() {
  const { command } = await inquirer.prompt([
    {
      type: "list",
      name: "command",
      message: "Task Management:",
      choices: [
        { name: "📋 List all tasks", value: "list" },
        { name: "🔍 Get task by ID", value: "get" },
        { name: "🗑️  Delete task by ID", value: "delete" },
        { name: "📊 Queue status", value: "queue-status" },
        { name: "⚙️  Queue settings", value: "queue-settings" },
        { name: "🔧 Update queue settings", value: "queue-settings-update" },
        { name: "⬅️  Back to main menu", value: "back" }
      ]
    }
  ]);

  if (command === "back") return;

  try {
    switch (command) {
      case "list":
        const tasks = await get("/tasks");
        console.table(tasks);
        break;
      case "get":
        const { id } = await inquirer.prompt([
          { type: "input", name: "id", message: "Enter task ID:" }
        ]);
        const task = await get(`/tasks/${id}`);
        console.log(task);
        break;
      case "delete":
        const { deleteId } = await inquirer.prompt([
          {
            type: "input",
            name: "deleteId",
            message: "Enter task ID to delete:"
          }
        ]);
        const result = await del(`/tasks/${deleteId}`);
        console.log("Task deleted:", result);
        break;
      case "queue-status":
        const status = await get("/tasks/queue/status");
        console.log(status);
        break;
      case "queue-settings":
        const settings = await get("/tasks/queue/settings");
        console.log(settings);
        break;
      case "queue-settings-update":
        const answers = await inquirer.prompt([
          {
            type: "number",
            name: "batchSize",
            message: "Batch size:",
            default: 1
          },
          {
            type: "number",
            name: "concurrency",
            message: "Concurrency:",
            default: 1
          },
          {
            type: "confirm",
            name: "retryEnabled",
            message: "Enable retries?",
            default: true
          },
          {
            type: "number",
            name: "maxRetries",
            message: "Max retries:",
            default: 3
          },
          {
            type: "number",
            name: "retryDelay",
            message: "Retry delay (ms):",
            default: 5000
          },
          {
            type: "number",
            name: "processingInterval",
            message: "Processing interval (ms):",
            default: 5000
          }
        ]);

        const updateResult = await post("/tasks/queue/settings", answers);
        console.log("Queue settings updated:", updateResult);
        break;
    }
  } catch (error) {
    console.error(
      chalk.red("Error:"),
      error instanceof Error ? error.message : String(error)
    );
  }

  await inquirer.prompt([
    { type: "input", name: "continue", message: "Press Enter to continue..." }
  ]);
}

async function handleFileCommands() {
  const { command } = await inquirer.prompt([
    {
      type: "list",
      name: "command",
      message: "File Operations:",
      choices: [
        { name: "📋 List files in dataset", value: "list" },
        { name: "🔍 Get file record", value: "get" },
        { name: "➕ Set file record", value: "set" },
        { name: "🗑️  Remove file record", value: "remove" },
        {
          name: "📅 Get deleted files older than date",
          value: "deleted-older"
        },
        { name: "⬅️  Back to main menu", value: "back" }
      ]
    }
  ]);

  if (command === "back") return;

  try {
    switch (command) {
      case "list":
        const { dataset } = await inquirer.prompt([
          { type: "input", name: "dataset", message: "Dataset name:" }
        ]);
        const files = await get(`/files?dataset=${dataset}`);
        console.table(files);
        break;
      case "get":
        const getAnswers = await inquirer.prompt([
          { type: "input", name: "dataset", message: "Dataset name:" },
          { type: "input", name: "file", message: "File path:" }
        ]);
        const file = await get(
          `/files/${getAnswers.dataset}/${getAnswers.file}`
        );
        console.log(file);
        break;
      case "set":
        const setAnswers = await inquirer.prompt([
          { type: "input", name: "dataset", message: "Dataset name:" },
          { type: "input", name: "file", message: "File path:" },
          { type: "input", name: "output", message: "Output path (optional):" },
          { type: "input", name: "status", message: "Status (optional):" }
        ]);
        const payload: any = {};
        if (setAnswers.output) payload.output = setAnswers.output;
        if (setAnswers.status) payload.status = setAnswers.status;
        const setResult = await post(
          `/files/${setAnswers.dataset}/${setAnswers.file}`,
          payload
        );
        console.log(setResult);
        break;
      case "remove":
        const removeAnswers = await inquirer.prompt([
          { type: "input", name: "dataset", message: "Dataset name:" },
          { type: "input", name: "file", message: "File path:" },
          {
            type: "confirm",
            name: "soft",
            message: "Soft delete?",
            default: true
          }
        ]);
        const removeResult = await del(
          `/files/${removeAnswers.dataset}/${removeAnswers.file}`,
          {
            soft: removeAnswers.soft
          }
        );
        console.log(removeResult);
        break;
      case "deleted-older":
        const olderAnswers = await inquirer.prompt([
          { type: "input", name: "dataset", message: "Dataset name:" },
          {
            type: "input",
            name: "isoDate",
            message: "ISO date (e.g., 2024-01-01T00:00:00Z):"
          }
        ]);
        const olderFiles = await get(
          `/files/${olderAnswers.dataset}/deleted-older-than/${olderAnswers.isoDate}`
        );
        console.table(olderFiles);
        break;
    }
  } catch (error) {
    console.error(
      chalk.red("Error:"),
      error instanceof Error ? error.message : String(error)
    );
  }

  await inquirer.prompt([
    { type: "input", name: "continue", message: "Press Enter to continue..." }
  ]);
}

async function handleConfigCommands() {
  const { command } = await inquirer.prompt([
    {
      type: "list",
      name: "command",
      message: "Configuration:",
      choices: [
        { name: "📋 List config files", value: "list" },
        { name: "⚙️  Get settings", value: "settings" },
        { name: "📄 Get config file", value: "file" },
        { name: "⬅️  Back to main menu", value: "back" }
      ]
    }
  ]);

  if (command === "back") return;

  try {
    switch (command) {
      case "list":
        const configs = await get("/config/list");
        console.table(configs);
        break;
      case "settings":
        const { key } = await inquirer.prompt([
          {
            type: "input",
            name: "key",
            message: "Setting key (leave empty for all):"
          }
        ]);
        const settings = await get(
          "/config/settings",
          key ? { key } : undefined
        );
        console.log(settings);
        break;
      case "file":
        const { name } = await inquirer.prompt([
          { type: "input", name: "name", message: "Config file name:" }
        ]);
        const file = await get(`/config/files/${name}`);
        console.log(file);
        break;
    }
  } catch (error) {
    console.error(
      chalk.red("Error:"),
      error instanceof Error ? error.message : String(error)
    );
  }

  await inquirer.prompt([
    { type: "input", name: "continue", message: "Press Enter to continue..." }
  ]);
}

async function handleWatcherCommands() {
  const { command } = await inquirer.prompt([
    {
      type: "list",
      name: "command",
      message: "Watcher Control:",
      choices: [
        { name: "▶️  Start watcher", value: "start" },
        { name: "⏹️  Stop watcher", value: "stop" },
        { name: "📊 Get status", value: "status" },
        { name: "⬅️  Back to main menu", value: "back" }
      ]
    }
  ]);

  if (command === "back") return;

  try {
    switch (command) {
      case "start":
        const { watches } = await inquirer.prompt([
          {
            type: "input",
            name: "watches",
            message: "Watch paths (comma-separated):"
          }
        ]);
        const watchList = watches.split(",").map((w: string) => w.trim());
        const result = await post("/watcher/start", { watches: watchList });
        console.log(result);
        break;
      case "stop":
        const stopResult = await post("/watcher/stop");
        console.log(stopResult);
        break;
      case "status":
        const status = await get("/watcher/status");
        console.log(status);
        break;
    }
  } catch (error) {
    console.error(
      chalk.red("Error:"),
      error instanceof Error ? error.message : String(error)
    );
  }

  await inquirer.prompt([
    { type: "input", name: "continue", message: "Press Enter to continue..." }
  ]);
}

async function handleMaintenanceCommands() {
  const { command } = await inquirer.prompt([
    {
      type: "list",
      name: "command",
      message: "Maintenance:",
      choices: [
        { name: "🧹 Cleanup missing files", value: "cleanup" },
        { name: "🗑️  Purge old records", value: "purge" },
        { name: "✂️  Prune processed files", value: "prune" },
        { name: "⬅️  Back to main menu", value: "back" }
      ]
    }
  ]);

  if (command === "back") return;

  try {
    switch (command) {
      case "cleanup":
        const { cleanupFile } = await inquirer.prompt([
          {
            type: "input",
            name: "cleanupFile",
            message: "File path to cleanup:"
          }
        ]);
        const cleanupResult = await post("/maintenance/cleanup", {
          file: cleanupFile
        });
        console.log(cleanupResult);
        break;
      case "purge":
        const { threshold } = await inquirer.prompt([
          {
            type: "input",
            name: "threshold",
            message: "Threshold (e.g., 30d, 1w):"
          }
        ]);
        const purgeResult = await post("/maintenance/purge", { threshold });
        console.log(purgeResult);
        break;
      case "prune":
        const pruneResult = await post("/maintenance/prune");
        console.log(pruneResult);
        break;
    }
  } catch (error) {
    console.error(
      chalk.red("Error:"),
      error instanceof Error ? error.message : String(error)
    );
  }

  await inquirer.prompt([
    { type: "input", name: "continue", message: "Press Enter to continue..." }
  ]);
}

async function handleHandbrakeCommands() {
  const { command } = await inquirer.prompt([
    {
      type: "list",
      name: "command",
      message: "HandBrake:",
      choices: [
        { name: "📋 List presets", value: "presets" },
        { name: "🎬 Process file", value: "process" },
        { name: "⬅️  Back to main menu", value: "back" }
      ]
    }
  ]);

  if (command === "back") return;

  try {
    switch (command) {
      case "presets":
        const presets = await get("/handbrake/presets");
        console.log(presets);
        break;
      case "process":
        const processAnswers = await inquirer.prompt([
          { type: "input", name: "input", message: "Input file path:" },
          { type: "input", name: "output", message: "Output file path:" },
          {
            type: "input",
            name: "preset",
            message: "Preset name:",
            default: "Fast 1080p30"
          }
        ]);
        const processResult = await post("/handbrake/process", processAnswers);
        console.log(processResult);
        break;
    }
  } catch (error) {
    console.error(
      chalk.red("Error:"),
      error instanceof Error ? error.message : String(error)
    );
  }

  await inquirer.prompt([
    { type: "input", name: "continue", message: "Press Enter to continue..." }
  ]);
}

// Help command (should be last)
program
  .command("help", { isDefault: false })
  .description("Show CLI help and usage")
  .action(() => {
    program.outputHelp();
  });

// Default action when no command is provided - defaults to interactive mode
program.action((options) => {
  runInteractive();
});

program.parse();
