/**
 * Screenshot & snapshot tools: browser_take_screenshot, browser_snapshot.
 */
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
export function registerScreenshotTools(ext, bs) {
    const screenshotTool = {
        name: "browser_take_screenshot",
        label: "Browser Take Screenshot",
        description: "Take a screenshot of the current page or viewport. " +
            "Saves to the output directory. Use browser_snapshot for text-based page analysis.",
        promptSnippet: "`browser_take_screenshot` — capture a screenshot of the page",
        parameters: {
            type: "object",
            properties: {
                filename: {
                    type: "string",
                    description: "Filename for the screenshot (default: screenshot-<timestamp>.png).",
                },
                fullPage: {
                    type: "boolean",
                    description: "Capture the full scrollable page, not just the viewport. Default: false.",
                },
                type: {
                    type: "string",
                    enum: ["png", "jpeg"],
                    description: "Image format. Default: png.",
                },
            },
        },
        async execute(_toolCallId, params) {
            const p = params;
            try {
                const page = bs.getActivePage();
                const config = bs.getConfig();
                mkdirSync(config.outputDir, { recursive: true });
                const filename = p.filename ?? `screenshot-${Date.now()}.${p.type ?? "png"}`;
                const filepath = join(config.outputDir, filename);
                await page.screenshot({
                    path: filepath,
                    fullPage: p.fullPage ?? false,
                    type: p.type ?? "png",
                });
                return {
                    content: [{
                            type: "text",
                            text: `✓ Screenshot saved: ${filepath}\nURL: ${page.url()}`,
                        }],
                    details: {},
                };
            }
            catch (err) {
                const msg = err instanceof Error ? err.message : String(err);
                return { content: [{ type: "text", text: `Screenshot failed: ${msg}` }], details: { isError: true } };
            }
        },
    };
    const snapshotTool = {
        name: "browser_snapshot",
        label: "Browser Snapshot",
        description: "Capture the accessibility snapshot of the current page. " +
            "This provides a structured text representation of the page content, " +
            "which is much more useful for understanding page structure and interacting " +
            "with elements than a screenshot. Each interactive element gets a unique ref.",
        promptSnippet: "`browser_snapshot` — get text-based page structure",
        parameters: {
            type: "object",
            properties: {
                filename: {
                    type: "string",
                    description: "Filename to save the snapshot to (default: snapshot-<timestamp>.txt).",
                },
            },
        },
        async execute(_toolCallId, params) {
            const p = params;
            try {
                const page = bs.getActivePage();
                const config = bs.getConfig();
                // Inject ARIA snapshot helper
                const snapshot = await page.evaluate(() => {
                    function buildSnapshot(element, depth) {
                        if (depth > 20)
                            return ""; // Prevent infinite recursion
                        let result = "";
                        const indent = "  ".repeat(depth);
                        const tag = element.tagName.toLowerCase();
                        const role = element.getAttribute("role");
                        const ariaLabel = element.getAttribute("aria-label");
                        const id = element.id ? `#${element.id}` : "";
                        const className = element.className && typeof element.className === "string"
                            ? `.${element.className.split(" ").filter(Boolean).join(".")}`
                            : "";
                        const text = element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE
                            ? ` "${element.textContent?.trim()}"`
                            : "";
                        // Build element description
                        let desc = `${indent}${tag}${id}${className}`;
                        if (role)
                            desc += ` [role=${role}]`;
                        if (ariaLabel)
                            desc += ` [aria-label="${ariaLabel}"]`;
                        if (text && text.length < 100)
                            desc += text;
                        // Interactive hints
                        const href = element.href;
                        const placeholder = element.placeholder;
                        const value = element.value;
                        if (href)
                            desc += ` → ${href}`;
                        if (placeholder)
                            desc += ` placeholder="${placeholder}"`;
                        if (value)
                            desc += ` value="${value.slice(0, 50)}"`;
                        result += desc + "\n";
                        for (const child of element.children) {
                            result += buildSnapshot(child, depth + 1);
                        }
                        return result;
                    }
                    return buildSnapshot(document.body ?? document.documentElement, 0);
                });
                mkdirSync(config.outputDir, { recursive: true });
                const filename = p.filename ?? `snapshot-${Date.now()}.txt`;
                const filepath = join(config.outputDir, filename);
                writeFileSync(filepath, snapshot, "utf-8");
                const truncated = snapshot.length > 50000
                    ? snapshot.slice(0, 50000) + `\n\n[truncated — full snapshot saved to ${filepath}]`
                    : snapshot;
                return {
                    content: [{
                            type: "text",
                            text: `Saved to: ${filepath}\nURL: ${page.url()}\n\n${truncated}`,
                        }],
                    details: {},
                };
            }
            catch (err) {
                const msg = err instanceof Error ? err.message : String(err);
                return { content: [{ type: "text", text: `Snapshot failed: ${msg}` }], details: { isError: true } };
            }
        },
    };
    for (const tool of [screenshotTool, snapshotTool]) {
        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`);
        }
    }
}
