#!/usr/bin/env node

import { createPlugin } from "./index.mjs";

function printJSON(value) {
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}

async function main() {
  const plugin = createPlugin();
  const [, , command = "describe", toolName, rawInput] = process.argv;

  if (command === "describe") {
    const toolsByProfile = Object.fromEntries(
      Object.keys(plugin.manifest.profiles).map(profileName => [
        profileName,
        createPlugin({ profile: profileName }).listTools()
      ]),
    );
    printJSON({
      manifest: plugin.manifest,
      profile: process.env.PRODUCTIER_TOOL_PROFILE || "readonly",
      tools: plugin.listTools(),
      toolsByProfile
    });
    return;
  }

  if (command === "call") {
    if (!toolName) {
      throw new Error("tool name is required: node src/cli.mjs call <toolName> '{\"workspaceSlug\":\"personal\"}'");
    }

    let input = {};
    if (rawInput) {
      try {
        input = JSON.parse(rawInput);
      } catch {
        throw new Error("input must be valid JSON");
      }
    }

    const result = await plugin.runTool(toolName, input);
    printJSON(result);
    process.exitCode = result.ok ? 0 : 1;
    return;
  }

  throw new Error(`unknown command: ${command}`);
}

main().catch(error => {
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
  process.exit(1);
});
