/**
 * Evaluate tools: browser_evaluate, browser_run_code_unsafe.
 */
export function registerEvaluateTools(ext, bs) {
    const evaluateTool = {
        name: "browser_evaluate",
        label: "Browser Evaluate",
        description: "Evaluate a JavaScript expression on the page or on a specific element. " +
            "Returns the result as JSON. Use this to read page state or interact with the DOM.",
        promptSnippet: "`browser_evaluate { expression }` — run JS and get the result",
        parameters: {
            type: "object",
            properties: {
                expression: {
                    type: "string",
                    description: "JavaScript expression to evaluate. Use 'return' for complex logic. " +
                        "Example: 'document.title' or 'Array.from(document.querySelectorAll(\"a\")).map(a => a.href)'",
                },
                ref: {
                    type: "string",
                    description: "Snapshot reference to evaluate on. If provided, expression runs on the element identified by this ref.",
                },
            },
            required: ["expression"],
        },
        async execute(_toolCallId, params) {
            const { expression } = params;
            try {
                const page = bs.getActivePage();
                const result = await page.evaluate(expression);
                if (result === undefined) {
                    return { content: [{ type: "text", text: "undefined" }], details: {} };
                }
                const text = typeof result === "string"
                    ? result
                    : JSON.stringify(result, null, 2);
                return {
                    content: [{
                            type: "text",
                            text: text.length > 50000 ? text.slice(0, 50000) + "\n\n[truncated]" : text,
                        }],
                    details: {},
                };
            }
            catch (err) {
                const msg = err instanceof Error ? err.message : String(err);
                return { content: [{ type: "text", text: `Evaluate failed: ${msg}` }], details: { isError: true } };
            }
        },
    };
    const runCodeTool = {
        name: "browser_run_code_unsafe",
        label: "Browser Run Code (Unsafe)",
        description: "Run a Playwright code snippet in the Node.js server process. " +
            "WARNING: This executes arbitrary JavaScript and is RCE-equivalent. " +
            "Use only when browser_evaluate is insufficient.",
        promptSnippet: "`browser_run_code_unsafe { code }` — run arbitrary Node.js+Playwright code",
        parameters: {
            type: "object",
            properties: {
                code: {
                    type: "string",
                    description: "A JavaScript function body that receives (page) as argument. " +
                        "Example: 'await page.goto(\"https://example.com\"); return await page.title();'",
                },
            },
            required: ["code"],
        },
        async execute(_toolCallId, params) {
            const { code } = params;
            try {
                const page = bs.getActivePage();
                // Create an async function from the code string with page in scope
                const fn = new Function("page", `return (async () => { ${code} })()`);
                const result = await fn(page);
                if (result === undefined) {
                    return { content: [{ type: "text", text: "undefined" }], details: {} };
                }
                const text = typeof result === "string"
                    ? result
                    : JSON.stringify(result, null, 2);
                return {
                    content: [{
                            type: "text",
                            text: text.length > 50000 ? text.slice(0, 50000) + "\n\n[truncated]" : text,
                        }],
                    details: {},
                };
            }
            catch (err) {
                const msg = err instanceof Error ? err.message : String(err);
                return { content: [{ type: "text", text: `Run code failed: ${msg}` }], details: { isError: true } };
            }
        },
    };
    for (const tool of [evaluateTool, runCodeTool]) {
        try {
            ext.registerTool(tool);
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            process.stderr.write(`[browser] Failed to register ${tool.name}: ${msg}\n`);
        }
    }
}
