"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerAuthTools = registerAuthTools;
const path = __importStar(require("path"));
const logger_1 = require("../../../lib/logger");
const playwright_1 = require("../playwright");
const schemas_1 = require("./schemas");
const helpers_1 = require("./helpers");
function registerAuthTools(srv) {
    // login_and_capture
    srv.registerTool('login_and_capture', {
        title: 'Login & Capture',
        description: 'Log into a website and optionally capture a screenshot of the authenticated page. ' +
            'Handles navigation, credential entry, form submission, and post-login waiting in one call. ' +
            'Returns a page handle for use with other tools. ' +
            'PREFERRED over separate navigate/fill/click calls for login flows. ' +
            'Common selectors: #username / #password / button[type="submit"]. ' +
            'If unsure about selectors, use extract_content first to discover the page structure.',
        inputSchema: schemas_1.loginAndCaptureSchema,
    }, async (args) => {
        try {
            const b = await (0, playwright_1.ensureBrowser)();
            const page = await b.newPage();
            const pageId = (0, playwright_1.allocatePageId)();
            playwright_1.pages.set(pageId, page);
            const timeout = args.timeout ?? 30_000;
            // Navigate to login page
            await page.goto(args.url, { waitUntil: 'load', timeout });
            // Fill credentials and submit
            await page.fill(args.username_selector, args.username, { timeout });
            await page.fill(args.password_selector, args.password, { timeout });
            await page.click(args.submit_selector, { timeout });
            // Wait for post-login indicator
            if (args.wait_after_login) {
                const indicator = args.wait_after_login;
                if (indicator.startsWith('/') || indicator.startsWith('http')) {
                    // URL pattern — wait until URL contains this string
                    await page.waitForFunction((pattern) => window.location.href.includes(pattern), indicator.startsWith('http') ? indicator : indicator, { timeout });
                    // Extra settle time for SPA data loading
                    await page.waitForTimeout(2000);
                }
                else {
                    // CSS selector
                    await page.waitForSelector(indicator, { timeout });
                }
            }
            else {
                // Default: wait for URL to change from login page
                const loginUrl = args.url;
                await page.waitForFunction((url) => !window.location.href.includes(url), loginUrl.replace(/https?:\/\/[^/]+/, ''), { timeout });
                await page.waitForTimeout(2000);
            }
            // Optional screenshot — handle directory-only paths gracefully
            let screenshot;
            if (args.screenshot_path) {
                let screenshotPath = args.screenshot_path;
                if (!path.extname(screenshotPath)) {
                    screenshotPath = screenshotPath.replace(/\/$/, '') + '/home.png';
                }
                screenshot = await (0, helpers_1.saveScreenshot)(page, screenshotPath, args.full_page ?? true);
            }
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            page_id: pageId,
                            url: page.url(),
                            title: await page.title(),
                            logged_in: true,
                            screenshot,
                            _handle: (0, playwright_1.buildHandle)(pageId),
                        }),
                    }],
            };
        }
        catch (err) {
            logger_1.loggerRegistry.error(`[lt-mcp:playwright-cli] login_and_capture error: ${err.message}`);
            return (0, helpers_1.errorResult)(err.message, err.name === 'TimeoutError' ? 'TIMEOUT' : 'LOGIN_FAILED');
        }
    });
    // capture_authenticated_pages
    srv.registerTool('capture_authenticated_pages', {
        title: 'Capture Authenticated Pages',
        description: 'Log in once, then navigate to multiple URLs capturing a screenshot of each. ' +
            'Reuses the same browser page so the authenticated session persists across all captures. ' +
            'PREFERRED for "login then screenshot all pages" tasks — handles the entire flow in one call.',
        inputSchema: schemas_1.captureAuthenticatedPagesSchema,
    }, async (args) => {
        try {
            const login = args.login;
            const b = await (0, playwright_1.ensureBrowser)();
            const page = await b.newPage();
            const pageId = (0, playwright_1.allocatePageId)();
            playwright_1.pages.set(pageId, page);
            const timeout = login.timeout ?? 30_000;
            // Login sequence
            await page.goto(login.url, { waitUntil: 'load', timeout });
            await page.fill(login.username_selector, login.username, { timeout });
            await page.fill(login.password_selector, login.password, { timeout });
            await page.click(login.submit_selector, { timeout });
            if (login.wait_after_login) {
                const indicator = login.wait_after_login;
                if (indicator.startsWith('/') || indicator.startsWith('http')) {
                    await page.waitForFunction((pattern) => window.location.href.includes(pattern), indicator, { timeout });
                    await page.waitForTimeout(2000);
                }
                else {
                    await page.waitForSelector(indicator, { timeout });
                }
            }
            else {
                const loginPath = login.url.replace(/https?:\/\/[^/]+/, '');
                await page.waitForFunction((path) => !window.location.href.includes(path), loginPath, { timeout });
                await page.waitForTimeout(2000);
            }
            // Capture each page (same browser page = same session)
            const captures = [];
            for (const target of args.pages) {
                await page.goto(target.url, { waitUntil: 'load', timeout: 30_000 });
                if (target.wait_for_selector) {
                    await page.waitForSelector(target.wait_for_selector, { timeout: 10_000 });
                }
                else {
                    await page.waitForTimeout(target.wait_ms ?? 3000);
                }
                const shot = await (0, helpers_1.saveScreenshot)(page, target.screenshot_path, target.full_page ?? true);
                captures.push({
                    url: page.url(),
                    title: await page.title(),
                    ...shot,
                });
            }
            return {
                content: [{
                        type: 'text',
                        text: JSON.stringify({
                            page_id: pageId,
                            login_url: login.url,
                            captures,
                            total: captures.length,
                            _handle: (0, playwright_1.buildHandle)(pageId),
                        }),
                    }],
            };
        }
        catch (err) {
            return (0, helpers_1.errorResult)(err.message, err.name === 'TimeoutError' ? 'TIMEOUT' : 'CAPTURE_FAILED');
        }
    });
}
