import { z } from 'zod';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { config } from '../../config.js';
import { detectProject } from '../../lib/frameworks/detect.js';
import { readComposerJson } from '../../lib/frameworks/composer.js';
import { errorResult, jsonResult, toErrorMessage } from '../shared.js';

function extractMajorMinor(versionConstraint: string | undefined): string {
  if (!versionConstraint) return '11.x';
  const match = versionConstraint.match(/(\d+)\.(\d+)/);
  if (!match) return '11.x';
  const [, major, minor] = match;
  return `${major}.${minor}`;
}

export function registerSearchLaravelDocsTool(server: McpServer): void {
  server.registerTool(
    'search_laravel_docs',
    {
      title: 'Search Laravel Docs',
      description:
        'Return a deep link to the Laravel documentation for a topic, version-matched to the laravel/framework constraint in composer.json.',
      inputSchema: {
        topic: z.string().min(1).describe('Documentation topic, e.g. "eloquent" or "validation".'),
        version: z.string().optional().describe('Override the version segment, e.g. "11.x". Auto-detected by default.'),
      },
    },
    async ({ topic, version }) => {
      try {
        const detected = detectProject(config.workspaceRoot);
        const laravelRoot = detected.backend?.kind === 'laravel' ? detected.backend.root : config.workspaceRoot;
        const composerJson = readComposerJson(laravelRoot);
        const constraint = composerJson?.require?.['laravel/framework'];
        const docsVersion = version ?? extractMajorMinor(constraint) + '.x';
        const slug = topic.toLowerCase().replace(/\s+/g, '-');
        const url = `https://laravel.com/docs/${docsVersion}/${slug}`;
        return jsonResult({
          topic,
          version: docsVersion,
          composerConstraint: constraint ?? null,
          url,
          note: 'This is a best-effort documentation link. If the topic page does not exist, MDN/search engines may help refine the query.',
        });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
