import { z } from 'zod';
import type { ToolDef, ToolContext } from './types.js';

const CheckTaskStatusInput = z.object({
  task_id: z.string().uuid().describe('ID of the task to check'),
});

type CheckTaskStatusInputT = z.infer<typeof CheckTaskStatusInput>;

export const checkTaskStatusTool: ToolDef<CheckTaskStatusInputT> = {
  name: 'check_task_status',
  description: 'Check the status and output of a subtask by ID. Returns state, output_summary, and timing.',
  inputSchema: CheckTaskStatusInput,
  jsonSchema: {
    type: 'function',
    function: {
      name: 'check_task_status',
      description: 'Check the status and output of a subtask by ID.',
      parameters: {
        type: 'object',
        properties: {
          task_id: { type: 'string', description: 'ID of the task to check' },
        },
        required: ['task_id'],
      },
    },
  },

  async execute(input: CheckTaskStatusInputT, _projectRoot: string, context: ToolContext): Promise<unknown> {
    const { sql } = context;

    const [task] = await sql<{ id: string; state: string; output_summary: string | null; started_at: string | null; ended_at: string | null }[]>`
      SELECT id, state, output_summary, started_at, ended_at
      FROM tasks
      WHERE id = ${input.task_id}
    `;

    if (!task) {
      return { error: `Task ${input.task_id} not found` };
    }

    return {
      id: task.id,
      state: task.state,
      output_summary: task.output_summary,
      started_at: task.started_at,
      ended_at: task.ended_at,
    };
  },
};
