"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerNavigationTools = registerNavigationTools;
const logger_1 = require("../../../lib/logger");
const storage_1 = require("../../../lib/storage");
const browser_lifecycle_1 = require("./browser-lifecycle");
const schemas_1 = require("./schemas");
const vision_helper_1 = require("./vision-helper");
function registerNavigationTools(srv) {
    // ── navigate ─────────────────────────────────────────────
    srv.registerTool('navigate', {
        title: 'Navigate to URL',
        description: 'Navigate to a URL. Pass page_id or _handle to reuse an existing page (preserving session/cookies). ' +
            'Without page_id, opens a NEW page — no cookies from prior pages. ' +
            'IMPORTANT: After login, always pass the page_id to maintain the authenticated session.',
        inputSchema: schemas_1.navigateSchema,
    }, async (args) => {
        let page;
        let id;
        // Reuse existing page if page_id or _handle provided (preserves session/cookies)
        if (args.page_id || args._handle) {
            try {
                ({ page, pageId: id } = await (0, browser_lifecycle_1.resolvePage)(args));
            }
            catch (err) {
                if (err.code) {
                    return { content: [{ type: 'text', text: JSON.stringify({ error: err.message, code: err.code }) }], isError: true };
                }
                throw err;
            }
        }
        else {
            const b = await (0, browser_lifecycle_1.ensureBrowser)();
            page = await b.newPage();
            id = (0, browser_lifecycle_1.allocatePageId)();
            browser_lifecycle_1.pages.set(id, page);
        }
        await page.goto(args.url, {
            waitUntil: args.wait_until || 'load',
            timeout: 30_000,
        });
        const title = await page.title();
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify({
                        page_id: id,
                        url: args.url,
                        title,
                        _handle: (0, browser_lifecycle_1.buildHandle)(id),
                    }),
                }],
        };
    });
    // ── screenshot ───────────────────────────────────────────
    srv.registerTool('screenshot', {
        title: 'Take Screenshot',
        description: 'Capture a screenshot and save as PNG. Accepts _handle or page_id from a prior tool call ' +
            'for cross-activity access. Pass `url` for self-contained navigate+screenshot. ' +
            'When both url and page_id are provided, navigates the EXISTING page (preserving session).',
        inputSchema: schemas_1.screenshotSchema,
    }, async (args) => {
        let page;
        let pageId;
        if (args.url && (args.page_id || args._handle)) {
            // Navigate existing page to URL (preserves session/cookies), then screenshot
            try {
                ({ page, pageId } = await (0, browser_lifecycle_1.resolvePage)(args));
                await page.goto(args.url, {
                    waitUntil: args.wait_until || 'load',
                    timeout: 30_000,
                });
            }
            catch (err) {
                if (err.code) {
                    return { content: [{ type: 'text', text: JSON.stringify({ error: err.message, code: err.code }) }], isError: true };
                }
                throw err;
            }
        }
        else if (args.url) {
            // Self-contained mode: new page + navigate + screenshot (no session)
            const b = await (0, browser_lifecycle_1.ensureBrowser)();
            page = await b.newPage();
            pageId = (0, browser_lifecycle_1.allocatePageId)();
            browser_lifecycle_1.pages.set(pageId, page);
            await page.goto(args.url, {
                waitUntil: args.wait_until || 'load',
                timeout: 30_000,
            });
        }
        else {
            // Use _handle or page_id to find existing page
            try {
                ({ page, pageId } = await (0, browser_lifecycle_1.resolvePage)(args));
            }
            catch (err) {
                if (err.code) {
                    return { content: [{ type: 'text', text: JSON.stringify({ error: err.message, code: err.code }) }], isError: true };
                }
                throw err;
            }
        }
        // Write screenshot via storage backend (local or S3)
        const backend = (0, storage_1.getStorageBackend)();
        const localPath = await backend.getLocalPath(args.path);
        if (args.selector) {
            const element = await page.$(args.selector);
            if (!element) {
                return {
                    content: [{
                            type: 'text',
                            text: JSON.stringify({ error: `Element not found: ${args.selector}` }),
                        }],
                    isError: true,
                };
            }
            await element.screenshot({ path: localPath });
        }
        else {
            await page.screenshot({
                path: localPath,
                fullPage: args.full_page ?? false,
            });
        }
        const { size } = await backend.commitLocalPath(args.path, localPath);
        logger_1.loggerRegistry.info(`[lt-mcp:playwright] screenshot saved: ${args.path} (${size} bytes)`);
        const metadata = {
            page_id: pageId,
            path: args.path,
            size_bytes: size,
            url: page.url(),
            _handle: (0, browser_lifecycle_1.buildHandle)(pageId),
        };
        // Auto-analyze via vision LLM when requested
        if (args.describe) {
            try {
                const description = await (0, vision_helper_1.analyzeScreenshot)(args.path);
                metadata.description = description;
            }
            catch (err) {
                metadata.description = null;
                metadata.describe_error = err.message;
            }
        }
        return {
            content: [{
                    type: 'text',
                    text: JSON.stringify(metadata),
                }],
        };
    });
}
