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

interface MdnSearchResult {
  documents?: Array<{
    mdn_url: string;
    title: string;
    summary: string;
    locale: string;
  }>;
}

export function registerSearchMdnTool(server: McpServer): void {
  server.registerTool(
    'search_mdn',
    {
      title: 'Search MDN',
      description: 'Search MDN for a web platform API, CSS property, or HTML element and return the top results.',
      inputSchema: {
        query: z.string().min(1).describe('Search query, e.g. "Array.prototype.map" or "fetch API".'),
        limit: z.number().int().positive().optional().default(5).describe('Maximum number of results to return.'),
      },
    },
    async ({ query, limit }) => {
      try {
        const url = `https://developer.mozilla.org/api/v1/search?q=${encodeURIComponent(query)}&locale=en-US`;
        const response = await fetch(url, { headers: { Accept: 'application/json' } });
        if (!response.ok) {
          throw new Error(`MDN search returned HTTP ${response.status}`);
        }
        const data = (await response.json()) as MdnSearchResult;
        const results =
          data.documents?.slice(0, limit).map((doc) => ({
            title: doc.title,
            url: `https://developer.mozilla.org${doc.mdn_url}`,
            summary: doc.summary,
          })) ?? [];
        return jsonResult({ query, results });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
