import { z } from 'zod';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { errorResult, jsonResult, toErrorMessage } from '../shared.js';
import { browserManager } from './browserManager.js';

export function registerBrowserNavigateTool(server: McpServer): void {
  server.registerTool(
    'browser_navigate',
    {
      title: 'Browser Navigate',
      description:
        'Open a URL in a headless/headed Playwright browser session. Reuses the same session across calls, so later tools (screenshot, inspect_dom, click, etc.) operate on the same page.',
      inputSchema: {
        url: z.string().url().describe('URL to navigate to, e.g. the local dev server URL from start_dev_server.'),
        headless: z.boolean().optional().default(true).describe('Run browser headlessly.'),
        waitUntil: z
          .enum(['load', 'domcontentloaded', 'networkidle'])
          .optional()
          .default('load')
          .describe('When to consider navigation complete.'),
        resetLogs: z
          .boolean()
          .optional()
          .default(true)
          .describe('Clear previously captured console logs before navigating.'),
      },
    },
    async ({ url, headless, waitUntil, resetLogs: shouldResetLogs }) => {
      try {
        const session = await browserManager.getSession(headless);
        if (shouldResetLogs) browserManager.resetLogs();
        const response = await session.page.goto(url, { waitUntil });
        const title = await session.page.title().catch(() => '');
        return jsonResult({
          url,
          title,
          status: response?.status() ?? null,
          finalUrl: response?.url() ?? url,
        });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
