import { z } from "zod";
import { defineCommand, arg } from "politty";
import { executeCommand, success, silentFailure } from "../lib/command-result";
import { runDocModules } from "./modules";
import { runDocModule } from "./module";
import { runDocSearch } from "./search";

const formatArg = arg(z.enum(["text", "json"]).default("text"), {
  alias: "f",
  description: "Output format (text or json)",
});

const modulesCommand = defineCommand({
  name: "modules",
  description: "List all modules with capabilities overview",
  args: z.object({
    format: formatArg,
  }),
  run: (args) => {
    return executeCommand(() => {
      const exitCode = runDocModules(args.format);
      return exitCode === 0 ? success() : silentFailure(exitCode);
    });
  },
});

const moduleCommand = defineCommand({
  name: "module",
  description: "Show documentation for a specific module",
  args: z.object({
    name: arg(z.string(), {
      positional: true,
      description: "Module name",
    }),
    type: arg(z.string().optional(), {
      positional: true,
      description: "Doc type (command, query, model, feature)",
    }),
    docName: arg(z.string().optional(), {
      positional: true,
      description: "Doc name",
    }),
    format: formatArg,
  }),
  run: (args) => {
    return executeCommand(() => {
      const exitCode = runDocModule(args.name, args.type, args.docName, args.format);
      return exitCode === 0 ? success() : silentFailure(exitCode);
    });
  },
});

const searchCommand = defineCommand({
  name: "search",
  description: "Search across all module documentation",
  args: z.object({
    query: arg(z.string(), {
      positional: true,
      description: "Search query",
    }),
    type: arg(z.string().optional(), {
      alias: "t",
      description: "Filter by doc type (command, query, model, feature, readme)",
    }),
    format: formatArg,
  }),
  run: (args) => {
    return executeCommand(() => {
      const exitCode = runDocSearch(args.query, args.type, args.format);
      return exitCode === 0 ? success() : silentFailure(exitCode);
    });
  },
});

export const docCommand = defineCommand({
  name: "doc",
  description: "Browse module documentation",
  subCommands: {
    modules: modulesCommand,
    module: moduleCommand,
    search: searchCommand,
  },
});
