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

interface ProcessStatusArgs {
  id: string;
}

export function createProcessStatusTool(manager: ProcessManager): Tool {
  return {
    name: 'process.status',
    description: 'Check the status of a background process by its ID.',
    inputSchema: {
      type: 'object',
      properties: {
        id: { type: 'string', description: 'Process ID (e.g. "proc_1")' },
      },
      required: ['id'],
    },
    execute: async (rawArgs: unknown): Promise<ToolResult> => {
      const args = rawArgs as ProcessStatusArgs;
      const proc = manager.get(args.id);
      if (!proc) {
        return { success: false, output: '', error: `Process ${args.id} not found` };
      }

      const uptime = proc.status === 'running'
        ? `${Math.round((Date.now() - proc.startedAt) / 1000)}s`
        : 'N/A';

      let info = `Process: ${proc.id}\n`;
      info += `Command: ${proc.command}\n`;
      info += `PID: ${proc.pid}\n`;
      info += `Status: ${proc.status}\n`;
      info += `Uptime: ${uptime}\n`;
      if (proc.exitCode !== undefined) {info += `Exit code: ${proc.exitCode}\n`;}
      if (proc.errorMessage) {info += `Error: ${proc.errorMessage}\n`;}
      if (proc.cwd) {info += `CWD: ${proc.cwd}\n`;}

      return { success: true, output: info.trimEnd() };
    },
  };
}
