export const name = 'install-tool';
export const description = 'Install an npm package and register it in the tools registry';

export async function execute(ctx) {
  const raw = ctx.args?.topic || ctx.args?.target || ctx.args?.task || '';
  if (!raw) return { success: false, reply: 'No package name provided. Usage: "install pdf-parse"' };

  // Extract package name (strip "install" prefix if user said "install pdf-parse")
  const packageName = raw.replace(/^install\s+/i, '').trim().split(/\s+/)[0];
  if (!packageName) return { success: false, reply: 'Could not determine package name.' };

  // Check if already registered
  const registry = ctx.getToolsRegistry();
  if (registry.includes(`\`${packageName}\``)) {
    return { success: true, reply: `Package \`${packageName}\` is already registered in tools.md.` };
  }

  // Install
  const result = await ctx.installTool(packageName);

  if (result.success) {
    ctx.addEvent('skill', 'agent', `Installed package: ${packageName}`, { skill: name, package: packageName });
    return { success: true, reply: `Successfully installed \`${packageName}\` and added it to the tools registry.` };
  } else {
    return { success: false, reply: `Failed to install \`${packageName}\`: ${result.error}` };
  }
}
