import * as vscode from 'vscode';
import { HandlerContext } from './types';
import { sanitizeCommand } from '../../security';

export async function applyRunCommandActions(ctx: HandlerContext): Promise<void> {
    const { aiMessage, rootPath, report } = ctx;
    let match: RegExpExecArray | null;
    // Action 5: Run Command
    const cmdRegex = /<run_command>([\s\S]*?)<\/run_command>/gi;
    while ((match = cmdRegex.exec(aiMessage)) !== null) {
        const cmd = match[1].trim();
        try {
            const safeCmd = sanitizeCommand(cmd);
            const terminal = vscode.window.terminals.find(t => t.name === 'Astra Terminal') || vscode.window.createTerminal({ name: 'Astra Terminal', cwd: rootPath });
            terminal.show();
            terminal.sendText(safeCmd);
            report.push(`🚀 Executed: ${safeCmd}`);
        } catch (err: any) { report.push(`❌ Blocked: ${err.message}`); }
    }
}
