import { resolve } from "node:path";
import { createPluginRunner, discoverPlugins } from "@wrnexus/plugin";
import { loadAppConfig } from "@wrnexus/styles";

export async function runPluginCliCommand(
  appRoot: string,
  commandName: string,
  args: string[],
): Promise<boolean> {
  const root = resolve(appRoot);
  const config = await loadAppConfig(root);
  const discovered = await discoverPlugins(root, config.plugins, {
    includeDevDependencies: true,
    strict: true,
  });
  const runner = createPluginRunner(discovered, {
    root,
    mode: "development",
    command: "cli",
    metadata: new Map(),
    warn: (message) => console.warn(`[wrnexus:plugin] ${message}`),
  });
  await runner.configure(config as Record<string, unknown>);
  await runner.configResolved(config as Readonly<Record<string, unknown>>);
  const command = (await runner.contributions()).cliCommands.find(
    (candidate) => candidate.name === commandName,
  );
  if (!command) return false;
  await command.run(args, {
    root,
    mode: "development",
    command: "cli",
    metadata: new Map(),
    warn: (message) => console.warn(`[wrnexus:plugin] ${message}`),
  });
  return true;
}
