/**
 * Vigthoria Terminal AI Integration
 * 
 * Enables the AI to execute terminal commands, read output, and iterate.
 * Like Cursor/Windsurf terminal integration.
 * 
 * - Creates managed terminals for AI operations
 * - Command execution with output capture
 * - Error detection and auto-fix suggestions
 * - Safe command validation
 */

const vscode = require('vscode');
const { SECURITY_CONFIG } = require('../utils/config');

class VightoriaTerminalIntegration {
    constructor() {
        this.terminals = new Map();   // name -> terminal
        this.outputs = new Map();     // name -> output buffer
        this.maxTerminals = 3;
        
        console.log('[TERMINAL-AI] ✨ Initialized');
    }

    register(context) {
        context.subscriptions.push(
            vscode.commands.registerCommand('vigthoria.runInTerminal',
                (command, opts) => this.executeCommand(command, opts)),
            vscode.commands.registerCommand('vigthoria.getTerminalOutput',
                (name) => this.getOutput(name)),
        );

        // Listen for terminal close events
        context.subscriptions.push(
            vscode.window.onDidCloseTerminal((terminal) => {
                for (const [name, t] of this.terminals) {
                    if (t === terminal) {
                        this.terminals.delete(name);
                        this.outputs.delete(name);
                        break;
                    }
                }
            })
        );

        console.log('[TERMINAL-AI] ✅ Registered');
    }

    /**
     * Execute a command in a managed terminal
     */
    async executeCommand(command, options = {}) {
        const {
            name = 'Vigthoria Agent',
            cwd = null,
            show = true,
            waitForCompletion = false,
            timeout = 30000
        } = options;

        // Validate command safety
        if (!this._isCommandSafe(command)) {
            const allow = await vscode.window.showWarningMessage(
                `AI wants to run: ${command}\n\nThis command may be destructive. Allow?`,
                { modal: true },
                'Allow', 'Cancel'
            );
            if (allow !== 'Allow') {
                return { success: false, reason: 'User denied command' };
            }
        }

        // Get or create terminal
        let terminal = this.terminals.get(name);
        if (!terminal) {
            if (this.terminals.size >= this.maxTerminals) {
                // Close oldest terminal
                const oldest = this.terminals.keys().next().value;
                this.terminals.get(oldest).dispose();
                this.terminals.delete(oldest);
                this.outputs.delete(oldest);
            }

            const workspaceRoot = cwd || 
                (vscode.workspace.workspaceFolders?.[0]?.uri.fsPath) || 
                process.env.HOME;

            terminal = vscode.window.createTerminal({
                name,
                cwd: workspaceRoot,
                env: {
                    VIGTHORIA_AGENT: '1',
                    TERM: 'xterm-256color'
                }
            });
            this.terminals.set(name, terminal);
            this.outputs.set(name, []);
        }

        if (show) {
            terminal.show(true); // true = preserveFocus
        }

        // Send the command
        terminal.sendText(command);

        return { 
            success: true, 
            command, 
            terminal: name,
            message: `Command sent to terminal: ${name}`
        };
    }

    /**
     * Get recent output from a terminal
     */
    getOutput(name = 'Vigthoria Agent') {
        return this.outputs.get(name) || [];
    }

    /**
     * Execute multiple commands sequentially
     */
    async executeSequence(commands, options = {}) {
        const results = [];
        for (const cmd of commands) {
            const result = await this.executeCommand(cmd, options);
            results.push(result);
            
            if (!result.success) break;
            
            // Small delay between commands
            await new Promise(resolve => setTimeout(resolve, 500));
        }
        return results;
    }

    /**
     * Check if a command is safe to run
     */
    _isCommandSafe(command) {
        const trimmed = command.trim().toLowerCase();
        
        // Dangerous patterns
        const dangerous = [
            /^rm\s+-rf?\s+\/(?!\w)/,        // rm -rf / (but allow rm -rf ./something)
            /^dd\s+/,                         // dd command
            /^mkfs/,                          // format disk
            /^fdisk/,                         // partition
            /^shutdown/,                      // system shutdown
            /^reboot/,                        // system reboot
            />\s*\/dev\/sd/,                  // write to disk device
            /^chmod\s+777\s+\//,              // chmod 777 on root paths
            /^curl.*\|\s*(?:bash|sh)/,        // pipe curl to shell
            /^wget.*\|\s*(?:bash|sh)/,        // pipe wget to shell
            /\brm\s+-rf\s+~\b/,              // rm -rf home
            /^sudo\s+rm/,                     // sudo rm
        ];

        for (const pattern of dangerous) {
            if (pattern.test(trimmed)) {
                return false;
            }
        }

        // Safe patterns (always allowed)
        const safe = [
            /^npm\s+(install|run|test|build|start)/,
            /^yarn\s+(add|install|run|build|test)/,
            /^pnpm\s+(add|install|run|build|test)/,
            /^git\s+(status|log|diff|add|commit|push|pull|branch|checkout)/,
            /^node\s+/,
            /^python3?\s+/,
            /^pip\s+(install|list)/,
            /^ls\b/,
            /^pwd\b/,
            /^cat\b/,
            /^echo\b/,
            /^mkdir\s+-p?\s+/,
            /^touch\b/,
            /^cd\b/,
            /^grep\b/,
            /^find\b/,
            /^head\b/,
            /^tail\b/,
            /^wc\b/,
        ];

        for (const pattern of safe) {
            if (pattern.test(trimmed)) {
                return true;
            }
        }

        // Unknown commands — ask user
        return false;
    }

    /**
     * Dispose all terminals
     */
    dispose() {
        for (const terminal of this.terminals.values()) {
            terminal.dispose();
        }
        this.terminals.clear();
        this.outputs.clear();
    }
}

module.exports = { VightoriaTerminalIntegration };
