import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { config } from '../../config.js';
import { detectProject, resolvePackage } from '../../lib/frameworks/detect.js';
import { resolveTarget } from '../../lib/frameworks/resolve.js';
import { runCommand } from '../../lib/runCommand.js';
import { errorResult, jsonResult, packageSchema, targetSchema, toErrorMessage } from '../shared.js';

export function registerBuildProjectTool(server: McpServer): void {
  server.registerTool(
    'build_project',
    {
      title: 'Build Project',
      description:
        'Run the production build: the JS bundle build for React, or `composer install --no-dev --optimize-autoloader` for Laravel/CodeIgniter. Surfaces build errors/warnings. Optional `package` scopes to a monorepo package.',
      inputSchema: { target: targetSchema, package: packageSchema },
    },
    async ({ target, package: packageName }) => {
      try {
        const root = packageName
          ? resolvePackage(config.workspaceRoot, packageName).pkg.absolutePath
          : config.workspaceRoot;
        const detected = detectProject(root);
        const { adapter, target: resolvedTarget } = resolveTarget(detected, target);
        const cmd = adapter.buildCommand();
        if (!cmd) {
          return jsonResult({
            target: resolvedTarget,
            package: packageName ?? null,
            adapter: adapter.label,
            ran: false,
            message: 'No build command configured for this project (no "build" script found).',
          });
        }
        const result = await runCommand(cmd.command, cmd.args, {
          cwd: cmd.cwd,
          timeoutMs: config.scaffoldCommandTimeoutMs,
        });
        return jsonResult({
          target: resolvedTarget,
          package: packageName ?? null,
          adapter: adapter.label,
          ran: true,
          exitCode: result.exitCode,
          timedOut: result.timedOut,
          failed: result.failed,
          output: result.output,
          cwd: result.cwd,
        });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
