/**
 * Playwright action tool for browser automation via MCP.
 *
 * Provides the judge with browser automation capabilities
 * to interact with and evaluate the generated application.
 */
import { z } from "zod";
import { createToolFactory, ToolCategory } from "../../agent/tools2/types.js";
/**
 * Input schema for Playwright action tool.
 */
const playwrightActionSchema = z.object({
    action: z
        .enum([
        "navigate",
        "click",
        "fill",
        "screenshot", // currently disabled, leads to prompt_too_long errors
        "getText",
        "waitForSelector",
        "evaluate",
        "getUrl",
        "reload",
    ])
        .describe("The Playwright action to perform"),
    params: z.record(z.any()).describe("Action-specific parameters").optional(),
});
/**
 * Creates a Playwright action tool factory.
 *
 * This tool allows the judge to perform browser automation
 * actions through the Playwright MCP server.
 */
export const playwrightActionToolFactory = createToolFactory("playwright_action", (playwrightBridge) => ({
    description: `Execute browser automation actions via Playwright.

Available actions:
- navigate: Go to a URL (params: { url: string })
- click: Click an element (params: { selector: string })
- fill: Fill an input field (params: { selector: string, value: string })
- screenshot: Capture screenshot (params: { fullPage?: boolean })
- getText: Get text from element (params: { selector: string })
- waitForSelector: Wait for element (params: { selector: string, timeout?: number })
- evaluate: Run JavaScript in browser context (params: { script: string }) - NOTE: Use plain JavaScript only, NO import/export/require statements
- getUrl: Get current URL (no params)
- reload: Reload page (no params)

Examples:
- Navigate: { action: "navigate", params: { url: "http://localhost:3000" } }
- Click button: { action: "click", params: { selector: "button[type=submit]" } }
- Fill input: { action: "fill", params: { selector: "#email", value: "test@example.com" } }
- Get text: { action: "getText", params: { selector: "h1" } }
- Screenshot: { action: "screenshot", params: { fullPage: true } }`,
    category: ToolCategory.GENERAL,
    inputSchema: playwrightActionSchema,
    // This is a read-only tool from the filesystem perspective
    readOnly: true,
    toModelOutput: (output) => {
        if ("screenshot" in output) {
            return {
                type: "content",
                value: [
                    {
                        type: "media",
                        data: output.screenshot,
                        mediaType: "image/png",
                    },
                ],
            };
        }
        else {
            return {
                type: "json",
                value: output,
            };
        }
    },
    execute: async ({ action, params = {} }) => {
        console.log("🎭 Playwright Tool: Executing action", {
            action,
            hasParams: Object.keys(params).length > 0,
            paramKeys: Object.keys(params),
        });
        // Pre-validate evaluate action to provide better error messages
        if (action === "evaluate" && params.script) {
            const script = params.script;
            console.log("🎭 Playwright Tool: Evaluate action detected", {
                scriptLength: script.length,
                scriptPreview: script.slice(0, 100),
            });
            if (script.includes("import ") ||
                script.includes("export ") ||
                script.includes("require(")) {
                console.log("🎭 Playwright Tool: Detected import/export/require in script, returning error");
                // Return instructive error instead of failing
                return {
                    success: false,
                    error: "Your JavaScript code contains import/export/require statements which cannot run in a browser console. Please rewrite using plain JavaScript. For example: instead of 'import React from \"react\"', check if React exists with 'typeof window.React !== \"undefined\"'. Use document.querySelector() to find elements.",
                    suggestion: "Try using browser APIs directly: document.querySelector, window.location, etc.",
                };
            }
        }
        console.log("🎭 Playwright Tool: Calling playwrightBridge.executeAction");
        const result = await playwrightBridge.executeAction(action, params);
        if (!result.success) {
            // Return error to model so it can retry with corrected approach
            return {
                success: false,
                error: result.error || "Action failed",
                suggestion: action === "evaluate"
                    ? "Make sure your JavaScript code is browser-compatible (no imports/exports)"
                    : undefined,
            };
        }
        // Format response based on action type
        switch (action) {
            case "navigate":
                return {
                    success: true,
                    message: `Navigated to ${params.url}`,
                };
            case "click":
                return {
                    success: true,
                    message: `Clicked element: ${params.selector}`,
                };
            case "fill":
                return {
                    success: true,
                    message: `Filled ${params.selector} with value`,
                };
            case "screenshot":
                // Screenshots are currently disabled to prevent prompt_too_long errors
                return {
                    success: false,
                    message: "tool is unavailable",
                };
            case "getText":
                return {
                    success: true,
                    text: result.data,
                };
            case "getUrl":
                return {
                    success: true,
                    url: result.data,
                };
            case "evaluate":
                return {
                    success: true,
                    result: result.data,
                };
            case "waitForSelector":
                return {
                    success: true,
                    message: `Element found: ${params.selector}`,
                };
            case "reload":
                return {
                    success: true,
                    message: "Page reloaded",
                };
            default:
                return {
                    success: true,
                    data: result.data,
                };
        }
    },
}));
//# sourceMappingURL=playwright-action.js.map