import { Type } from '@sinclair/typebox';
import type { ToolDefinition } from '@mariozechner/pi-coding-agent';
import type { CoordService } from '../../coord/coord.service.js';

export function createCoordTools(coordService: CoordService): ToolDefinition[] {
  const getMissionStatus: ToolDefinition = {
    name: 'coord_mission_status',
    label: 'Mission Status',
    description:
      'Get the current orchestration mission status including milestones, tasks, and active session.',
    parameters: Type.Object({
      projectPath: Type.Optional(
        Type.String({ description: 'Project path. Defaults to gateway working directory.' }),
      ),
    }),
    async execute(_toolCallId, params) {
      const { projectPath } = params as { projectPath?: string };
      const resolvedPath = projectPath ?? process.cwd();
      const status = await coordService.getMissionStatus(resolvedPath);
      return {
        content: [
          {
            type: 'text' as const,
            text: status ? JSON.stringify(status, null, 2) : 'No active coord mission found.',
          },
        ],
        details: undefined,
      };
    },
  };

  const listCoordTasks: ToolDefinition = {
    name: 'coord_list_tasks',
    label: 'List Coord Tasks',
    description: 'List all tasks from the orchestration TASKS.md file.',
    parameters: Type.Object({
      projectPath: Type.Optional(
        Type.String({ description: 'Project path. Defaults to gateway working directory.' }),
      ),
    }),
    async execute(_toolCallId, params) {
      const { projectPath } = params as { projectPath?: string };
      const resolvedPath = projectPath ?? process.cwd();
      const tasks = await coordService.listTasks(resolvedPath);
      return {
        content: [{ type: 'text' as const, text: JSON.stringify(tasks, null, 2) }],
        details: undefined,
      };
    },
  };

  const getCoordTaskDetail: ToolDefinition = {
    name: 'coord_task_detail',
    label: 'Coord Task Detail',
    description: 'Get detailed status for a specific orchestration task.',
    parameters: Type.Object({
      taskId: Type.String({ description: 'Task ID (e.g. P2-005)' }),
      projectPath: Type.Optional(
        Type.String({ description: 'Project path. Defaults to gateway working directory.' }),
      ),
    }),
    async execute(_toolCallId, params) {
      const { taskId, projectPath } = params as { taskId: string; projectPath?: string };
      const resolvedPath = projectPath ?? process.cwd();
      const detail = await coordService.getTaskStatus(resolvedPath, taskId);
      return {
        content: [
          {
            type: 'text' as const,
            text: detail
              ? JSON.stringify(detail, null, 2)
              : `Task ${taskId} not found in coord mission.`,
          },
        ],
        details: undefined,
      };
    },
  };

  return [getMissionStatus, listCoordTasks, getCoordTaskDetail];
}
