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

export function registerDetectFrameworkTool(server: McpServer): void {
  server.registerTool(
    'detect_framework',
    {
      title: 'Detect Framework',
      description:
        'Inspect the workspace (or a monorepo package) and report which framework adapter(s) were detected: laravel, codeigniter, symfony, django, rails, react, vue, nuxt, a backend+frontend combination, or generic. Call this first.',
      inputSchema: {
        package: z
          .string()
          .optional()
          .describe('Optional monorepo package name/path to inspect instead of the workspace root.'),
        includeWorkspace: z
          .boolean()
          .optional()
          .default(false)
          .describe('If true, also include a packages[] summary from detect_workspace.'),
      },
    },
    async ({ package: packageName, includeWorkspace }) => {
      try {
        const root = packageName
          ? resolvePackage(config.workspaceRoot, packageName).pkg.absolutePath
          : config.workspaceRoot;
        const detected = detectProject(root);
        const summary = summarizeDetection(detected) as Record<string, unknown>;
        if (includeWorkspace) {
          summary.workspace = summarizeWorkspace(detectWorkspace(config.workspaceRoot));
        }
        if (packageName) summary.package = packageName;
        return jsonResult(summary);
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}

export function registerDetectWorkspaceTool(server: McpServer): void {
  server.registerTool(
    'detect_workspace',
    {
      title: 'Detect Workspace Packages',
      description:
        'Scan the workspace for monorepo packages (apps/*, packages/*, services/*, frontend/client/web, package.json workspaces, pnpm-workspace.yaml) and report each package’s detected framework adapter(s).',
      inputSchema: {},
    },
    async () => {
      try {
        return jsonResult(summarizeWorkspace(detectWorkspace(config.workspaceRoot)));
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
