import { z } from "zod";
import { defineCommand, arg } from "politty";
import { runInit } from "./init";
import { runUpdate } from "./update";
import { runLicenseCheck, runLicenseList } from "./license";
import { moduleCommand } from "./module/index";
import { appCommand } from "./app/index";
import { mockCommand } from "./mock/index";
import { docCommand } from "./doc/index";
import { executeCommand, success, silentFailure } from "./lib/command-result";

export { moduleCommand } from "./module/index";
export { appCommand } from "./app/index";
export { mockCommand } from "./mock/index";
export { docCommand } from "./doc/index";

const cwd = process.cwd();

export const initCommand = defineCommand({
  name: "init",
  description: "First-time setup for a consumer repo",
  args: z.object({
    name: arg(z.string(), {
      positional: true,
      description: "Project name",
    }),
  }),
  run: (args) => {
    return executeCommand(() => {
      const exitCode = runInit(args.name, cwd);
      return exitCode === 0 ? success() : silentFailure(exitCode);
    });
  },
});

export const updateCommand = defineCommand({
  name: "update",
  description: "Refresh framework-managed resources (skills, workflows)",
  args: z.object({
    resources: arg(z.array(z.string()).default([]), {
      positional: true,
      description: "Resources to update (skills, workflows). Defaults to all.",
    }),
  }),
  run: (args) => {
    return executeCommand(() => {
      const exitCode = runUpdate(cwd, args.resources);
      return exitCode === 0 ? success() : silentFailure(exitCode);
    });
  },
});

const licenseCheckCommand = defineCommand({
  name: "check",
  description: "Check dependency licenses against allowlist",
  args: z.object({
    config: arg(z.string(), {
      alias: "c",
      description: "Path to license config JSON file",
    }),
  }),
  run: (args) => {
    return executeCommand(() => {
      const exitCode = runLicenseCheck(args.config);
      return exitCode === 0 ? success() : silentFailure(exitCode);
    });
  },
});

const licenseListCommand = defineCommand({
  name: "list",
  description: "List available license groups",
  run: () => {
    return executeCommand(() => {
      const exitCode = runLicenseList();
      return exitCode === 0 ? success() : silentFailure(exitCode);
    });
  },
});

const licenseCommand = defineCommand({
  name: "license",
  description: "License management",
  subCommands: {
    check: licenseCheckCommand,
    list: licenseListCommand,
  },
});

export const mainCommand = defineCommand({
  name: "erp-kit",
  description: "ERP module framework CLI",
  subCommands: {
    module: moduleCommand,
    app: appCommand,
    mock: mockCommand,
    doc: docCommand,
    init: initCommand,
    update: updateCommand,
    license: licenseCommand,
  },
});
