/**
 * Command executor for Devicely CLI
 */

const { spawn } = require('child_process');
const path = require('path');
const chalk = require('chalk');

// Import deviceDetection from appropriate location
let discoverAllDevices;
try {
    ({ discoverAllDevices } = require('./deviceDetection'));
} catch (err) {
    ({ discoverAllDevices } = require('../../deviceDetection'));
}

async function executeCommand(command, options = {}) {
    const devices = await discoverAllDevices();
    
    if (!devices || devices.length === 0) {
        console.log(chalk.red('\n❌ No devices found'));
        return;
    }

    let targetDevices = devices.filter(d => d.status === 'online');
    
    if (options.device) {
        targetDevices = devices.filter(d => 
            d.name === options.device && d.status === 'online'
        );
        
        if (targetDevices.length === 0) {
            console.log(chalk.red(`\n❌ Device "${options.device}" not found or offline`));
            return;
        }
    }

    if (targetDevices.length === 0) {
        console.log(chalk.yellow('\n⚠️  No online devices found'));
        return;
    }

    console.log(chalk.cyan(`\nExecuting on ${targetDevices.length} device(s):`));
    targetDevices.forEach(d => console.log(`  • ${d.name}`));
    console.log('');

    const scriptDir = path.join(__dirname, '../../scripts/shell');
    
    for (const device of targetDevices) {
        const platform = device.platform;
        const type = device.type;
        
        let scriptName;
        if (platform === 'ios' && type === 'usb') {
            scriptName = 'connect_ios_usb_multi_final.sh';
        } else if (platform === 'ios' && type === 'wireless') {
            scriptName = 'connect_ios_wireless_multi_final.sh';
        } else if (platform === 'android' && type === 'usb') {
            scriptName = 'connect_android_usb_multi_final.sh';
        } else if (platform === 'android' && type === 'wireless') {
            scriptName = 'connect_android_wireless_multi_final.sh';
        } else {
            console.log(chalk.yellow(`⚠️  Unsupported device type: ${platform}-${type}`));
            continue;
        }

        const scriptPath = path.join(scriptDir, scriptName);
        
        console.log(chalk.blue(`[${device.name}] Running command...`));
        
        const child = spawn(scriptPath, ['-d', device.name, ...command.split(' ')], {
            stdio: 'pipe'
        });

        child.stdout.on('data', (data) => {
            const lines = data.toString().split('\n').filter(l => l.trim());
            lines.forEach(line => {
                console.log(chalk.gray(`  ${line}`));
            });
        });

        child.stderr.on('data', (data) => {
            const lines = data.toString().split('\n').filter(l => l.trim());
            lines.forEach(line => {
                console.log(chalk.red(`  ${line}`));
            });
        });

        await new Promise((resolve) => {
            child.on('close', (code) => {
                if (code === 0) {
                    console.log(chalk.green(`[${device.name}] ✅ Success\n`));
                } else {
                    console.log(chalk.red(`[${device.name}] ❌ Failed (exit code: ${code})\n`));
                }
                resolve();
            });
        });
    }
}

module.exports = {
    executeCommand
};
