/**
 * @fileoverview Prerequisites checker for mobile development environment
 * 
 * This script verifies that all necessary tools and configurations are in place
 * for mobile app development, including both Android and iOS platforms.
 * 
 * Features:
 * - Validates development environment setup
 * - Checks required command-line tools
 * - Verifies Android SDK and device connectivity
 * - Confirms iOS development tools and simulator status
 * 
 * Prerequisites checked:
 * - Node.js and npm installation
 * - Gradle for Android builds
 * - Xcode and command line tools for iOS
 * - ANDROID_HOME environment variable
 * - Android platform files
 * - Connected Android devices/emulators
 * - iOS platform files
 * - Running iOS simulators
 * 
 * Exit codes:
 * - 0: All checks passed
 * - 1: One or more checks failed
 * 
 * @example
 * // Run directly
 * node scripts/check-prerequisites.js
 * 
 * // Run via npm script
 * npm run test:prerequisites
 * 
 * @author TimeSafari Team
 * @license MIT
 */

const { execSync } = require('child_process');
const { existsSync } = require('fs');

/**
 * Checks if a command-line tool is available by attempting to run its --version command
 * 
 * @param {string} command - The command to check (e.g., 'node', 'npm', 'gradle')
 * @param {string} errorMessage - The error message to display if the command is not available
 * @returns {boolean} - True if the command exists and is executable, false otherwise
 * 
 * @example
 * checkCommand('node', 'Node.js is required')
 * // Returns true if node is available, false otherwise
 */
function checkCommand(command, errorMessage) {
    try {
        execSync(command + ' --version', { stdio: 'ignore' });
        return true;
    } catch (e) {
        console.error(`❌ ${errorMessage}`);
        return false;
    }
}

/**
 * Verifies Android development environment setup
 * 
 * Checks for:
 * 1. ANDROID_HOME environment variable
 * 2. Android platform files in project
 * 3. Connected Android devices or running emulators
 * 
 * @returns {boolean} - True if Android setup is complete and valid, false otherwise
 * 
 * @example
 * if (!checkAndroidSetup()) {
 *     console.error('Android prerequisites not met');
 * }
 */
function checkAndroidSetup() {
    // Check ANDROID_HOME environment variable
    // This is required for Android SDK tools access
    if (!process.env.ANDROID_HOME) {
        console.error('❌ ANDROID_HOME environment variable not set');
        return false;
    }

    // Check if Android platform was added to the project
    // The 'android' directory should exist if platform was added via 'npx cap add android'
    if (!existsSync('android')) {
        console.error('❌ Android platform not added. Run: npx cap add android');
        return false;
    }

    // Check for connected devices or running emulators
    // Uses ADB (Android Debug Bridge) to list connected devices
    try {
        const devices = execSync('adb devices').toString();
        // Parse ADB output - looking for lines ending with 'device' (not 'offline' or 'unauthorized')
        if (!devices.split('\n').slice(1).some(line => line.includes('device'))) {
            console.error('❌ No Android devices connected');
            return false;
        }
    } catch (e) {
        console.error('❌ ADB not available');
        return false;
    }

    return true;
}

/**
 * Verifies iOS development environment setup
 * 
 * Checks for:
 * 1. iOS platform files in project
 * 2. Running iOS simulators
 * 3. Xcode command line tools availability
 * 
 * @returns {boolean} - True if iOS setup is complete and valid, false otherwise
 * 
 * @example
 * if (!checkIosSetup()) {
 *     console.error('iOS prerequisites not met');
 * }
 */
function checkIosSetup() {
    // Check if iOS platform was added to the project
    // The 'ios' directory should exist if platform was added via 'npx cap add ios'
    if (!existsSync('ios')) {
        console.error('❌ iOS platform not added. Run: npx cap add ios');
        return false;
    }

    // Check for available and running iOS simulators
    // Uses xcrun simctl to list simulator devices
    try {
        const simulators = execSync('xcrun simctl list devices available').toString();
        if (!simulators.includes('Booted')) {
            console.error('❌ No iOS simulator running');
            return false;
        }
    } catch (e) {
        console.error('❌ Xcode command line tools not available');
        return false;
    }

    return true;
}

/**
 * Main function to check all prerequisites for mobile development
 * 
 * Verifies:
 * 1. Required command line tools (node, npm, gradle, xcodebuild)
 * 2. Android development setup
 * 3. iOS development setup
 * 
 * Exits with code 1 if any checks fail
 * 
 * @example
 * // Run from package.json script:
 * // "test:prerequisites": "node scripts/check-prerequisites.js"
 */
function main() {
    let success = true;

    // Check required command line tools
    // These are essential for building and testing the application
    success &= checkCommand('node', 'Node.js is required');
    success &= checkCommand('npm', 'npm is required');
    success &= checkCommand('gradle', 'Gradle is required for Android builds');
    success &= checkCommand('xcodebuild', 'Xcode is required for iOS builds');

    // Check platform-specific development environments
    success &= checkAndroidSetup();
    success &= checkIosSetup();

    // Exit with error if any checks failed
    if (!success) {
        process.exit(1);
    }

    console.log('✅ All prerequisites met!');
}

// Execute the checks
main();