// =============================================================================
// Pure shell execution API — no ToolContext coupling.
// =============================================================================

import * as cp from 'child_process';
import * as util from 'util';
import { safeResolve } from './utils';

const execAsync = util.promisify(cp.exec);

const BLOCKED_COMMANDS = ['rm -rf /', 'mkfs', ':(){:|:&};:'];

export async function executeCommand(
    workspaceRoot: string,
    command: string,
    workingDirectory?: string
): Promise<unknown> {
    if (BLOCKED_COMMANDS.some(b => command.includes(b))) {
        return { error: 'Command blocked for safety.' };
    }
    const cwd = workingDirectory ? safeResolve(workspaceRoot, workingDirectory) : workspaceRoot;
    try {
        const { stdout, stderr } = await execAsync(command, {
            cwd, timeout: 120_000, maxBuffer: 1024 * 1024,
        });
        return { exitCode: 0, stdout: stdout.trim(), stderr: stderr.trim() };
    } catch (err: any) {
        return {
            exitCode: err.code,
            stdout: (err.stdout || '').trim(),
            stderr: (err.stderr || '').trim(),
            error: err.message,
        };
    }
}
