import path from "node:path";
import z from "zod";
import { getPrefixedLogger } from "../../../util/logger.js";
import { createToolFactory, PermissionLevel, ToolCategory, } from "../tools2/types.js";
export const buildReloadFileToolFactory = createToolFactory("build_reloadFile", ({ clark, services, }) => {
    return {
        category: ToolCategory.GENERAL,
        defaultPermission: PermissionLevel.ALLOW,
        readOnly: true,
        description: `
Reload a part of the app.

If a file path is provided, we will trigger a Hot Module Replacement (HMR) and remount the components in the app. 
File paths are relative (e.g. "pages/Home/index.tsx").

Use this tool with a path when:
- You update an API that is run off a useEffect that should be re-evaluated.
- You need to re-trigger some logic that only runs on component mount or file evaluation.

If no file path is provided, we will trigger a full reload of the app. This can be useful if the app is not rendering after an initial generation.

**IMPORTANT:**
This tool should NOT be used as a first resort for fixing app issues. Examine error logs or build errors first.
`,
        inputSchema: z.object({
            filePath: z
                .string()
                .optional()
                .describe("Relative path to the file to reload (e.g., 'pages/Home/index.tsx')"),
        }),
        execute: async ({ filePath }) => {
            if (!services.viteServer) {
                throw new Error("Vite server is not available. This tool can only be used in development mode.");
            }
            const logger = getPrefixedLogger(`[reloadFile]`);
            if (!filePath) {
                // Trigger full iframe reload through the socket connection
                await clark.context.peer?.call.reloadIframe();
                logger.info("Reload tool - full reload via socket");
                return {
                    message: "Successfully triggered full reload",
                    filePath: undefined,
                };
            }
            const fullPath = path.join(services.appShell.appRootDirPath, filePath);
            logger.info(`Reloading file: ${filePath} (full path: ${fullPath})`);
            const module = services.viteServer.moduleGraph.getModuleById(fullPath);
            if (!module) {
                throw new Error(`Module not found for file: ${filePath}. The file may not have been imported yet.`);
            }
            // Invalidate the module
            services.viteServer.moduleGraph.invalidateModule(module);
            // Trigger immediate reload
            await services.viteServer.reloadModule(module);
            services.viteServer.ws.send({
                type: "custom",
                event: "sb:force-remount-after-reload",
                data: {},
            });
            logger.info(`Successfully reloaded file: ${filePath}`);
            return {
                message: `Successfully reloaded file: ${filePath}`,
                filePath,
            };
        },
        getSummary: (input) => {
            return {
                output: input.filePath ? "File reloaded" : "App reloaded",
            };
        },
    };
});
//# sourceMappingURL=build-reload-file.js.map