import { cmd } from "../cli/cmd/cmd"
import { generateHelp } from "./help"
import type { Argv } from "yargs"

export function createHelpCommand(root?: () => Argv) {
  return cmd({
    command: "help [command]",
    describe: "show full CLI reference",
    builder: (yargs) =>
      yargs
        .positional("command", {
          describe: "command to show help for",
          type: "string",
        })
        .option("all", {
          describe: "show help for all commands",
          type: "boolean",
          default: false,
        })
        .option("format", {
          describe: "output format",
          type: "string",
          choices: ["md", "text"] as const,
          default: "md" as const,
        }),
    async handler(args) {
      if (!args.command && !args.all) {
        if (root) {
          const help = await root().getHelp()
          process.stdout.write(help + "\n")
        }
        return
      }
      const output = await generateHelp({
        command: args.command,
        all: args.all,
        format: args.format as "md" | "text",
      })
      process.stdout.write(output + "\n")
    },
  })
}

// Static instance for introspection by commands.ts / help.ts (handler not invoked)
export const HelpCommand = createHelpCommand()
