import { z } from 'zod';
import { config } from '../../config.js';
import { runCommand } from '../../lib/runCommand.js';
import { errorResult, jsonResult, toErrorMessage } from '../shared.js';
import { isAllowedSparkCommand, SPARK_ALLOWED, SPARK_DESTRUCTIVE } from './sparkAllowList.js';
import { requireCodeIgniter } from './requireCodeIgniter.js';
export function registerSparkTool(server) {
    server.registerTool('spark', {
        title: 'Run Spark Command',
        description: 'Run a whitelisted `php spark` subcommand in the detected CodeIgniter 4 project and return stdout/stderr. ' +
            `Allowed commands: ${SPARK_ALLOWED.join(', ')}. ` +
            'Destructive command (migrate:refresh) requires confirm: true.',
        inputSchema: {
            command: z
                .string()
                .min(1)
                .describe('Spark subcommand, e.g. "make:controller" or "migrate".'),
            args: z
                .array(z.string())
                .optional()
                .default([])
                .describe('Arguments forwarded after the subcommand, e.g. ["PostController", "--resource"].'),
            confirm: z
                .boolean()
                .optional()
                .describe('Required as true for destructive command (migrate:refresh).'),
        },
    }, async ({ command, args, confirm }) => {
        try {
            if (!isAllowedSparkCommand(command)) {
                return errorResult(`Spark command "${command}" is not on the allow-list. Allowed: ${SPARK_ALLOWED.join(', ')}.`);
            }
            if (SPARK_DESTRUCTIVE.has(command) && confirm !== true) {
                return errorResult(`Spark command "${command}" is destructive and requires confirm: true.`);
            }
            const ci = requireCodeIgniter();
            const phpArgs = ['spark', command, ...(args ?? [])];
            const result = await runCommand('php', phpArgs, {
                cwd: ci.root,
                timeoutMs: config.scaffoldCommandTimeoutMs,
            });
            return jsonResult({
                sparkCommand: command,
                sparkArgs: args ?? [],
                exitCode: result.exitCode,
                timedOut: result.timedOut,
                failed: result.failed,
                output: result.output,
                cwd: result.cwd,
            });
        }
        catch (error) {
            return errorResult(toErrorMessage(error));
        }
    });
}
//# sourceMappingURL=spark.js.map