import { safeJsonParse, safeJsonStringify } from "../../util/log-sanitizer.js";
import { ToolExecutionError } from "./tools2/types.js";
// Define handlers with proper typing
// The MessageHandlers type ensures that each handler receives the correct
// argument type based on its key. TypeScript automatically infers the correct
// type for 'args' in each handler based on the tool name key.
const messageHandlers = {
    glob: () => undefined,
    grep: () => undefined,
    ls: () => undefined,
    build_writeFile: (args) => {
        return {
            filePath: args?.filePath ?? "",
            content: args?.content ?? "",
        };
    },
    build_getValidIcons: () => undefined,
    build_installPackages: (args) => {
        return {
            packages: args?.packages ?? [],
        };
    },
    build_readFile: (args) => ({
        filePath: args?.filePath ?? "",
        ranges: args?.ranges ?? [],
    }),
    build_reloadFile: (args) => ({
        filePath: args?.filePath ?? "",
    }),
    build_listFiles: () => undefined,
    build_generateApiSource: (args) => ({
        apiName: args?.apiName ?? "",
        action: args?.action ?? "create",
    }),
    build_debug: () => undefined,
    build_finalize: () => undefined,
    build_editFile: (args) => ({
        filePath: args?.filePath ?? "",
        oldString: args?.oldString ?? "",
        newString: args?.newString ?? "",
        replaceAll: args?.replaceAll ?? false,
    }),
    build_multiEditFile: (args) => ({
        filePath: args?.filePath ?? "",
        edits: args?.edits ?? [],
    }),
    build_renameFile: (args) => ({
        oldPath: args?.oldPath ?? "",
        newPath: args?.newPath ?? "",
    }),
    readIntegrationMetadata: (args, clark) => {
        const ids = args?.integrationIds;
        const integrationNames = clark?.context.availableIntegrations
            ?.filter((int) => ids?.includes(int.id))
            .map((int) => int.displayName ?? int.name);
        return {
            integrationNames: integrationNames ?? [],
        };
    },
    searchIntegrations: (args) => {
        const type = args?.type;
        const name = args?.name;
        return {
            type,
            name,
        };
    },
    executeRequestToIntegration: (args, clark) => {
        const integration = clark?.context.availableIntegrations?.find((int) => int.id === args?.integrationId);
        const integrationName = integration?.displayName ?? integration?.name ?? "";
        return {
            integrationName,
            integrationId: args?.integrationId,
            params: args?.params,
            description: args?.description,
        };
    },
    runCode: (args, clark) => {
        const integration = clark?.context.availableIntegrations?.find((int) => int.id === args?.integrationId);
        const integrationName = integration?.displayName ?? integration?.name ?? "";
        return {
            integrationName,
            integrationId: args?.integrationId,
            script: args?.script,
        };
    },
    writeApi: (args) => ({
        apiName: args?.apiName ?? "",
        apiSource: args?.apiSource ?? "",
    }),
    buildApi: (args) => ({
        apiName: args?.apiName ?? "",
    }),
    testApi: (args) => ({
        apiName: args?.apiName ?? "",
        inputs: args?.inputs ?? {},
    }),
    build_manageChecklist: () => undefined,
    build_deleteFile: (args) => ({
        filePath: args?.filePath ?? "",
        reason: args?.reason,
    }),
    browser_playwright_action: (args) => ({
        action: args?.action ?? "navigate",
        url: args?.url,
        selector: args?.selector,
        value: args?.value,
        fullPage: args?.fullPage,
        script: args?.script,
        eventName: args?.eventName,
        payload: args?.payload,
        properties: args?.properties,
    }),
    web_search: (args) => ({
        query: args?.query ?? "",
        allowed_domains: args?.allowed_domains,
        blocked_domains: args?.blocked_domains,
    }),
    web_fetch: (args) => ({
        url: args?.url ?? "",
        prompt: args?.prompt ?? "",
    }),
};
export async function getToolCallArguments(toolName, toolArguments, clark) {
    if (toolName in messageHandlers) {
        const handler = messageHandlers[toolName];
        if (handler) {
            const result = await handler(toolArguments, clark);
            return result;
        }
    }
    return undefined;
}
export function getToolOutput(toolName, output) {
    try {
        // For now only return result for executeRequestToIntegration
        if (toolName === "executeRequestToIntegration") {
            if (output?.data && typeof output.data === "string") {
                const isPartial = output.isPartial === true;
                const parsedOutput = safeJsonParse(output.data);
                if (parsedOutput === undefined) {
                    // Not valid JSON (e.g. HTML or plain text) — return raw data
                    return {
                        result: output.data,
                        count: 1,
                        ...(isPartial && { isPartial }),
                    };
                }
                if (Array.isArray(parsedOutput)) {
                    return {
                        result: parsedOutput.slice(0, 10),
                        count: parsedOutput.length,
                        ...(isPartial && { isPartial }),
                    };
                }
                return {
                    result: parsedOutput,
                    count: 1,
                    ...(isPartial && { isPartial }),
                };
            }
            return output;
        }
        if (toolName === "build_captureScreenshot") {
            return {
                screenshotFileName: output?.fileName,
            };
        }
        if (toolName === "browser_playwright_action") {
            return output;
        }
        // Web tools - pass through output directly
        if (toolName === "web_search" || toolName === "web_fetch") {
            return output;
        }
        return undefined;
    }
    catch {
        return undefined;
    }
}
export function getToolErrorCode(error) {
    if (error instanceof ToolExecutionError) {
        return error.code;
    }
    return undefined;
}
export function getToolErrorMessage(error) {
    try {
        if (error instanceof Error) {
            return error.message;
        }
        if (typeof error === "string") {
            return error;
        }
        if (typeof error === "object" && error !== null) {
            if ("message" in error) {
                return safeJsonStringify(error.message);
            }
            if ("error" in error) {
                return safeJsonStringify(error.error);
            }
            return safeJsonStringify(error);
        }
        return safeJsonStringify(error) ?? "Unknown error";
    }
    catch {
        return "Unknown error";
    }
}
//# sourceMappingURL=tool-message-utils.js.map