import select from "@inquirer/select";
import { defineCommand, arg } from "politty";
import { z } from "zod";
import { executeCommand, failure } from "../../lib/command-result";
import { listAppTemplates, runAppInit } from "./init";

export const initCommand = defineCommand({
  name: "init",
  description: "Bootstrap a new app with directory structure and README",
  args: z.object({
    name: arg(z.string(), {
      positional: true,
      description: "App name",
    }),
    dir: arg(z.string(), {
      positional: true,
      description: "Parent directory where the app will be created",
    }),
    template: arg(z.string().optional(), {
      alias: "t",
      description: "Template to use (interactive if omitted)",
    }),
  }),
  run: (args) => {
    return executeCommand(async () => {
      const templates = listAppTemplates();
      if (templates.length === 0) {
        return failure("No app templates found");
      }

      let template = args.template;
      if (template) {
        if (!templates.includes(template)) {
          return failure(`Template "${template}" not found. Available: ${templates.join(", ")}`);
        }
      } else if (templates.length === 1) {
        template = templates[0];
      } else {
        template = await select({
          message: "Select app template:",
          choices: templates.map((t) => ({ name: t, value: t })),
        });
      }

      return runAppInit(args.name, args.dir, template);
    });
  },
});
