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

export function registerGenerateCodeIgniterShieldAuthTool(server: McpServer): void {
  server.registerTool(
    'generate_codeigniter_shield_auth',
    {
      title: 'Scaffold CodeIgniter Shield Auth',
      description:
        'Install/setup CodeIgniter Shield auth helpers. Requires codeigniter4/shield. ' +
        'Runs `php spark shield:setup` (and optionally composer require). Requires confirm: true.',
      inputSchema: {
        installPackage: z
          .boolean()
          .optional()
          .default(false)
          .describe('If true and Shield is missing, run composer require codeigniter4/shield first.'),
        confirm: z.boolean().optional().describe('Required as true — Shield setup modifies project files.'),
      },
    },
    async ({ installPackage, confirm }) => {
      try {
        if (confirm !== true) {
          return errorResult('generate_codeigniter_shield_auth requires confirm: true.');
        }

        const ci = requireCodeIgniter();
        const composer = readComposerJson(ci.root);
        const steps: Array<Record<string, unknown>> = [];
        let hasShield = hasComposerDependency(composer, 'codeigniter4/shield');

        if (!hasShield && installPackage) {
          const requireResult = await runCommand(
            'composer',
            ['require', 'codeigniter4/shield', '--no-interaction'],
            { cwd: ci.root, timeoutMs: config.scaffoldCommandTimeoutMs },
          );
          steps.push({
            step: 'composer-require',
            exitCode: requireResult.exitCode,
            failed: requireResult.failed,
            output: requireResult.output,
          });
          if (requireResult.failed) {
            return errorResult(`Failed to install codeigniter4/shield:\n${requireResult.output}`);
          }
          hasShield = true;
        }

        if (!hasShield) {
          return errorResult(
            'codeigniter4/shield is not installed. Pass installPackage: true (with confirm: true) ' +
              'or run composer_require with package "codeigniter4/shield" first.',
          );
        }

        const setup = await runCommand('php', ['spark', 'shield:setup', '--no-interaction'], {
          cwd: ci.root,
          timeoutMs: config.scaffoldCommandTimeoutMs,
        });
        steps.push({ step: 'shield:setup', exitCode: setup.exitCode, failed: setup.failed, output: setup.output });

        return jsonResult({
          package: 'codeigniter4/shield',
          steps,
        });
      } catch (error) {
        return errorResult(toErrorMessage(error));
      }
    },
  );
}
