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

const ListTasksInput = z.object({
  parent_task_id: z.string().uuid().optional().describe('Filter by parent task ID. Omit to list children of current task.'),
});

type ListTasksInputT = z.infer<typeof ListTasksInput>;

export const listTasksTool: ToolDef<ListTasksInputT> = {
  name: 'list_tasks',
  description: 'List child tasks of the current task (or a specified parent). Returns id, state, input preview, and output_summary.',
  inputSchema: ListTasksInput,
  jsonSchema: {
    type: 'function',
    function: {
      name: 'list_tasks',
      description: 'List child tasks of the current task (or a specified parent).',
      parameters: {
        type: 'object',
        properties: {
          parent_task_id: { type: 'string', description: 'Filter by parent task ID. Omit to list children of current task.' },
        },
        required: [],
      },
    },
  },

  async execute(input: ListTasksInputT, _projectRoot: string, context: ToolContext): Promise<unknown> {
    const { sql } = context;
    const ctx = getInferenceContext();
    const parentId = input.parent_task_id ?? ctx.taskId;

    if (!parentId) {
      return { tasks: [], note: 'No parent task context — not running inside a task.' };
    }

    const rows = await sql<{ id: string; state: string; input: string; output_summary: string | null }[]>`
      SELECT id, state, input, output_summary
      FROM tasks
      WHERE parent_task_id = ${parentId}
      ORDER BY created_at DESC
      LIMIT 50
    `;

    return {
      tasks: rows.map((r) => ({
        id: r.id,
        state: r.state,
        input_preview: r.input.slice(0, 100),
        output_summary: r.output_summary,
      })),
    };
  },
};
