import { initCommand } from "./commands/init.js";
import { doctorCommand } from "./commands/doctor.js";
import { verifyCommand } from "./commands/verify.js";
import { runCommand } from "./commands/run.js";

function normalizeOptionName(name) {
  return name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
}

export function parseCliArgs(argv) {
  const args = [...argv].slice(2);
  const command = args.shift() || "help";
  const options = {};

  while (args.length > 0) {
    const token = args.shift();
    if (!token.startsWith("--")) {
      continue;
    }

    const rawName = token.slice(2);
    const optionName = normalizeOptionName(rawName);
    if (args.length === 0 || args[0].startsWith("--")) {
      options[optionName] = true;
      continue;
    }

    options[optionName] = args.shift();
  }

  return { command, options };
}

export async function runCli(argv) {
  const { command, options } = parseCliArgs(argv);

  switch (command) {
    case "init":
      return initCommand(options);
    case "doctor":
      return doctorCommand(options);
    case "verify":
      return verifyCommand(options);
    case "run":
      return runCommand(options);
    case "help":
    default:
      printHelp();
      return;
  }
}

function printHelp() {
  console.log(`Codex Harness CLI

Usage:
  harness init [--version <version>] [--project-root <path>] [--vendor] [--force] [--init-git] [--plan]
  harness doctor [--project-root <path>]
  harness verify [--project-root <path>]
  harness run [--project-root <path>] [--task-file <path>] [--run-until-done]
`);
}
