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

export function createProcessListTool(manager: ProcessManager): Tool {
  return {
    name: 'process.list',
    description: 'List all managed background processes and their current status.',
    inputSchema: {
      type: 'object',
      properties: {},
      required: [],
    },
    execute: async (): Promise<ToolResult> => {
      const procs = manager.list();
      if (procs.length === 0) {
        return { success: true, output: 'No managed processes.' };
      }

      const lines = procs.map(p => {
        const uptime = p.status === 'running'
          ? `${Math.round((Date.now() - p.startedAt) / 1000)}s`
          : 'N/A';
        let line = `${p.id}  PID=${p.pid}  status=${p.status}  uptime=${uptime}  cmd="${p.command}"`;
        if (p.exitCode !== undefined) {line += `  exit=${p.exitCode}`;}
        return line;
      });

      return { success: true, output: lines.join('\n') };
    },
  };
}
