/**
 * =============================================================================
 * IntelliCall AI - Environment Validation Helper
 * =============================================================================
 * This script validates that all required environment variables are set.
 * Used by both setup scripts and the backend on startup.
 * 
 * Run: node validate-env.js
 * =============================================================================
 */

const fs = require('fs');
const path = require('path');

// Colors for console output
const colors = {
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    reset: '\x1b[0m'
};

// Required environment variables
const REQUIRED_VARS = [
    { name: 'MONGODB_URI', description: 'MongoDB connection string' },
    { name: 'JWT_SECRET', description: 'JWT secret key (min 32 chars)' },
    { name: 'GOOGLE_CLIENT_ID', description: 'Google OAuth Client ID' },
    { name: 'GOOGLE_CLIENT_SECRET', description: 'Google OAuth Client Secret' },
    { name: 'BASE_URL', description: 'Backend Base URL (for callbacks)' },
    { name: 'CLIENT_URL', description: 'Frontend dashboard URL' }
];

/**
 * Load .env file if it exists
 */
function loadEnvFile(envPath) {
    if (!fs.existsSync(envPath)) {
        return null;
    }

    const content = fs.readFileSync(envPath, 'utf8');
    const env = {};

    content.split('\n').forEach(line => {
        line = line.trim();
        if (line && !line.startsWith('#')) {
            const [key, ...valueParts] = line.split('=');
            if (key) {
                env[key.trim()] = valueParts.join('=').trim();
            }
        }
    });

    return env;
}

/**
 * Validate environment variables
 */
function validateEnv(envPath = null) {
    console.log('');
    console.log(`${colors.blue}═══════════════════════════════════════════════════════════${colors.reset}`);
    console.log(`${colors.blue}  IntelliCall AI Environment Validation${colors.reset}`);
    console.log(`${colors.blue}═══════════════════════════════════════════════════════════${colors.reset}`);
    console.log('');

    // Try to load .env file
    let env = process.env;
    if (envPath) {
        const fileEnv = loadEnvFile(envPath);
        if (fileEnv) {
            env = { ...process.env, ...fileEnv };
            console.log(`${colors.green}✅ Loaded .env file${colors.reset}`);
        } else {
            console.log(`${colors.red}❌ .env file not found at ${envPath}${colors.reset}`);
            console.log('');
            console.log('   Run the setup wizard to create this file:');
            console.log('   - macOS/Linux: bash setup/setup.sh');
            console.log('   - Windows: .\\setup\\setup.ps1');
            console.log('');
            return { valid: false, missing: ['ENV_FILE'] };
        }
    }

    console.log('');

    // Check required variables
    console.log(`${colors.yellow}Checking required variables...${colors.reset}`);
    const missingRequired = [];

    REQUIRED_VARS.forEach(v => {
        if (!env[v.name] || env[v.name].includes('your_') || env[v.name].includes('YOUR_')) {
            console.log(`${colors.red}❌ ${v.name} - ${v.description}${colors.reset}`);
            missingRequired.push(v.name);
        } else {
            console.log(`${colors.green}✅ ${v.name}${colors.reset}`);
        }
    });

    // Summary
    console.log('');
    console.log(`${colors.blue}═══════════════════════════════════════════════════════════${colors.reset}`);

    if (missingRequired.length > 0) {
        console.log('');
        console.log(`${colors.red}❌ VALIDATION FAILED${colors.reset}`);
        console.log('');
        console.log('   Missing required variables:');
        missingRequired.forEach(v => console.log(`   • ${v}`));
        console.log('');
        console.log('   Please run the setup wizard or manually configure .env');
        console.log('');
        return { valid: false, missing: missingRequired };
    }

    console.log('');
    console.log(`${colors.green}✅ VALIDATION PASSED${colors.reset}`);

    console.log('');
    return { valid: true, missing: [] };
}

// Run if called directly
if (require.main === module) {
    const envPath = process.argv[2] || path.join(__dirname, '..', 'backend', '.env');
    const result = validateEnv(envPath);
    process.exit(result.valid ? 0 : 1);
}

module.exports = { validateEnv, REQUIRED_VARS };
