import z from "zod";
import { createToolFactory, ToolCategory } from "../tools2/types.js";
// Store checklist state in Clark context
const getChecklistState = (clark) => {
    if (!clark.context.checklist) {
        clark.context.checklist = {
            items: [],
            lastUpdated: new Date().toISOString(),
        };
    }
    return clark.context.checklist;
};
const updateChecklistState = (clark, newState) => {
    clark.context.checklist = {
        ...newState,
        lastUpdated: new Date().toISOString(),
    };
};
// Export function to be used by other tools
export const checkChecklistCompletion = (clark) => {
    const checklistState = getChecklistState(clark);
    const pendingTasks = checklistState.items.filter((item) => item.status === "pending" || item.status === "in_progress");
    return {
        complete: pendingTasks.length === 0,
        pendingTasks,
    };
};
export const buildManageChecklistToolFactory = createToolFactory("build_manageChecklist", ({ clark, services, }) => {
    return {
        category: ToolCategory.GENERAL,
        description: `
      Manage a dynamic checklist of tasks to complete during agent execution.
      Use this tool to create, update, and track progress on tasks.

      This tool supports:
      - Adding new checklist items
      - Updating item status (pending, in_progress, completed, cancelled)
      - Updating item content
      - Retrieving current checklist state

      The checklist helps organize complex multi-step tasks and provides visibility
      into agent progress for the user.
    `,
        inputSchema: z.object({
            action: z
                .enum(["add", "update", "get"])
                .describe("Action to perform on the checklist"),
            itemId: z
                .string()
                .optional()
                .describe("ID of the item to update (required for update action)"),
            content: z
                .string()
                .optional()
                .describe("Content/description of the checklist item"),
            status: z
                .enum(["pending", "in_progress", "completed", "cancelled"])
                .optional()
                .describe("Status of the checklist item"),
        }),
        execute: async ({ action, itemId, content, status }) => {
            const checklistState = getChecklistState(clark);
            switch (action) {
                case "add": {
                    if (!content) {
                        throw new Error("Content is required when adding a checklist item");
                    }
                    const newItem = {
                        id: `item_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                        content,
                        status: status || "pending",
                        createdAt: new Date().toISOString(),
                    };
                    const newState = {
                        ...checklistState,
                        items: [...checklistState.items, newItem],
                    };
                    updateChecklistState(clark, newState);
                    // Notify UI about the new item
                    await services.appShell.sendMessage({
                        type: "checklist_item_added",
                        payload: {
                            item: newItem,
                            totalItems: newState.items.length,
                        },
                    });
                    return {
                        success: true,
                        action: "add",
                        item: newItem,
                        message: `Added checklist item: "${content}"`,
                        totalItems: newState.items.length,
                    };
                }
                case "update": {
                    if (!itemId) {
                        throw new Error("Item ID is required when updating a checklist item");
                    }
                    const itemIndex = checklistState.items.findIndex((item) => item.id === itemId);
                    if (itemIndex === -1) {
                        throw new Error(`Checklist item with ID "${itemId}" not found`);
                    }
                    const existingItem = checklistState.items[itemIndex];
                    if (!existingItem) {
                        throw new Error(`Checklist item at index ${itemIndex} is undefined`);
                    }
                    const updatedItem = {
                        id: existingItem.id,
                        content: content || existingItem.content,
                        status: status || existingItem.status,
                        createdAt: existingItem.createdAt,
                        updatedAt: new Date().toISOString(),
                    };
                    const newItems = [...checklistState.items];
                    newItems[itemIndex] = updatedItem;
                    const newState = {
                        ...checklistState,
                        items: newItems,
                    };
                    updateChecklistState(clark, newState);
                    // Notify UI about the updated item
                    await services.appShell.sendMessage({
                        type: "checklist_item_updated",
                        payload: {
                            item: updatedItem,
                            completedItems: newState.items.filter((item) => item.status === "completed").length,
                            totalItems: newState.items.length,
                        },
                    });
                    return {
                        success: true,
                        action: "update",
                        item: updatedItem,
                        message: `Updated checklist item: "${updatedItem.content}"`,
                        completedItems: newState.items.filter((item) => item.status === "completed").length,
                        totalItems: newState.items.length,
                    };
                }
                case "get": {
                    const completedItems = checklistState.items.filter((item) => item.status === "completed").length;
                    return {
                        success: true,
                        action: "get",
                        items: checklistState.items,
                        completedItems,
                        totalItems: checklistState.items.length,
                        lastUpdated: checklistState.lastUpdated,
                        message: `Retrieved ${checklistState.items.length} checklist items`,
                    };
                }
                default:
                    throw new Error(`Unknown action: ${action}`);
            }
        },
        getSummary: (input, output) => {
            const action = input.action;
            const totalItems = output.totalItems ?? 0;
            const completedItems = output.completedItems ?? 0;
            return {
                input: `action: ${action}`,
                output: `${completedItems}/${totalItems} complete`,
            };
        },
    };
});
//# sourceMappingURL=build-manage-checklist.js.map