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

export function registerBrowserConsoleLogsTool(server: McpServer): void {
  server.registerTool(
    'browser_get_console_logs',
    {
      title: 'Browser Console Logs',
      description:
        'Return console logs, JavaScript page errors, and failed network requests captured since the last browser_navigate call (or since the browser session started).',
      inputSchema: {
        level: z
          .enum(['all', 'error', 'warn', 'log', 'info', 'debug'])
          .optional()
          .default('all')
          .describe('Filter logs by type.'),
        limit: z
          .number()
          .int()
          .positive()
          .optional()
          .default(100)
          .describe('Maximum number of logs to return.'),
      },
    },
    async ({ level, limit }) => {
      try {
        const session = await browserManager.getSession();
        let logs: ConsoleLog[] = session.consoleLogs.slice(-limit);
        if (level !== 'all') {
          logs = logs.filter((log) => log.type === level);
        }
        return jsonResult({
          totalCaptured: session.consoleLogs.length,
          returned: logs.length,
          logs,
        });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
