import type { Tool, ToolResult } from '../../types.js';
import type { ProcessManager } from './manager.js';

interface ProcessKillArgs {
  id: string;
  signal?: string;
}

export function createProcessKillTool(manager: ProcessManager): Tool {
  return {
    name: 'process.kill',
    description: 'Kill a background process by its ID.',
    inputSchema: {
      type: 'object',
      properties: {
        id: { type: 'string', description: 'Process ID (e.g. "proc_1")' },
        signal: { type: 'string', description: 'Signal to send (default: SIGTERM). Use SIGKILL for force kill.' },
      },
      required: ['id'],
    },
    execute: async (rawArgs: unknown): Promise<ToolResult> => {
      const args = rawArgs as ProcessKillArgs;
      try {
        const signal = (args.signal ?? 'SIGTERM') as NodeJS.Signals;
        const killed = manager.kill(args.id, signal);
        if (killed) {
          return { success: true, output: `Sent ${signal} to process ${args.id}` };
        }
        const proc = manager.get(args.id);
        return {
          success: false,
          output: '',
          error: `Process ${args.id} is not running (status: ${proc?.status ?? 'unknown'})`,
        };
      } catch (error) {
        return {
          success: false,
          output: '',
          error: error instanceof Error ? error.message : 'Failed to kill process',
        };
      }
    },
  };
}
