/**
 * System requirements checker for Devicely
 */

const { execSync } = require('child_process');
const chalk = require('chalk');

function checkCommand(command, name) {
    try {
        execSync(`which ${command}`, { stdio: 'ignore' });
        console.log(`${chalk.green('✓')} ${name} installed`);
        return true;
    } catch (error) {
        console.log(`${chalk.red('✗')} ${name} not found`);
        return false;
    }
}

function getVersion(command) {
    try {
        const version = execSync(command, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] });
        return version.trim().split('\n')[0];
    } catch (error) {
        return 'Unknown';
    }
}

async function checkDoctor() {
    console.log('\n📋 System Requirements Check\n');
    
    let allGood = true;
    
    // Node.js
    console.log(chalk.bold('Node.js:'));
    const nodeVersion = process.version;
    console.log(`${chalk.green('✓')} Version: ${nodeVersion}\n`);
    
    // iOS Tools
    console.log(chalk.bold('iOS Automation Tools:'));
    const hasXcode = checkCommand('xcodebuild', 'Xcode');
    const hasIdevice = checkCommand('idevice_id', 'libimobiledevice');
    const hasIproxy = checkCommand('iproxy', 'usbmuxd');
    allGood = allGood && hasXcode && hasIdevice && hasIproxy;
    console.log('');
    
    // Android Tools
    console.log(chalk.bold('Android Automation Tools:'));
    const hasAdb = checkCommand('adb', 'Android Debug Bridge (adb)');
    allGood = allGood && hasAdb;
    
    if (hasAdb) {
        const adbVersion = getVersion('adb --version');
        console.log(`  Version: ${adbVersion}`);
    }
    console.log('');
    
    // Python (for UIAutomator2)
    console.log(chalk.bold('Python:'));
    const hasPython = checkCommand('python3', 'Python 3');
    if (hasPython) {
        const pythonVersion = getVersion('python3 --version');
        console.log(`  Version: ${pythonVersion}`);
    }
    console.log('');
    
    // Summary
    if (allGood) {
        console.log(chalk.green.bold('✅ All requirements met!'));
        console.log(chalk.gray('\nYou can start using Devicely with: devicely start'));
    } else {
        console.log(chalk.yellow.bold('⚠️  Some requirements are missing'));
        console.log(chalk.gray('\n📖 Installation Guide:'));
        
        if (!hasIdevice || !hasIproxy) {
            console.log(chalk.gray('\nFor iOS support:'));
            console.log('  brew install libimobiledevice usbmuxd');
        }
        
        if (!hasAdb) {
            console.log(chalk.gray('\nFor Android support:'));
            console.log('  brew install android-platform-tools');
        }
        
        if (!hasPython) {
            console.log(chalk.gray('\nFor Python:'));
            console.log('  brew install python3');
        }
    }
    console.log('');
}

module.exports = {
    checkDoctor
};
