#!/usr/bin/env node
/**
 * ReePoe Start - Hybrid local/cloud startup
 */

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
const os = require('os');
const axios = require('axios');

// Detect cloud environment
function isCloudEnvironment() {
    return !!(
        process.env.REPL_ID ||           // Replit
        process.env.CODESPACE_NAME ||    // GitHub Codespaces
        process.env.GITPOD_WORKSPACE_ID  // Gitpod
    );
}

// Get binary path (FIXED - use require.resolve for correct npm path)
function getBinaryPath() {
    const platform = os.platform();
    const arch = os.arch();
    
    let binaryName;
    if (platform === 'darwin') {
        binaryName = arch === 'arm64' ? 'reepoe-macos-arm64' : 'reepoe-macos-x64';
    } else if (platform === 'linux') {
        binaryName = 'reepoe-linux-x64';
    } else if (platform === 'win32') {
        binaryName = 'reepoe-windows.exe';
    }
    
    // Use require.resolve to find the actual npm install location
    try {
        const packageRoot = path.dirname(require.resolve('reepoe/package.json'));
        const binaryPath = path.join(packageRoot, 'binaries', binaryName);
        return fs.existsSync(binaryPath) ? binaryPath : null;
    } catch (e) {
        // Fallback to relative path
        const binaryPath = path.join(__dirname, '../binaries', binaryName);
        return fs.existsSync(binaryPath) ? binaryPath : null;
    }
}

// Check if server is already running
async function isServerRunning(port) {
    try {
        await axios.get(`http://localhost:${port}/health`, { timeout: 2000 });
        return true;
    } catch (error) {
        return false;
    }
}

// ========== PHASE 3B: Activation Check ==========

async function checkActivationStatus() {
    const ActivationClient = require('../lib/activation-client');
    const client = new ActivationClient();
    const readline = require('readline');
    
    // Check for existing activation
    const activation = client.loadActivation();
    
    if (activation) {
        // Verify activation is still valid via API
        const check = await client.checkActivation(activation.email, require('../package.json').version);
        
        if (check.activated) {
            // Show expiry warning if needed
            if (check.warn_expiring) {
                console.log(`\n⚠️  Your access expires in ${check.days_remaining} days!`);
                console.log('   Request extension: reepoe extend-request\n');
            }
            
            // Check version
            if (check.update_required && check.critical_update) {
                console.log('\n🚨 CRITICAL SECURITY UPDATE REQUIRED');
                console.log(`   Your version: ${require('../package.json').version}`);
                console.log(`   Minimum version: ${check.latest_version}`);
                console.log('   Update: npm install -g reepoe@latest\n');
                process.exit(1);
            } else if (check.update_required) {
                console.log(`\nℹ️  Update available: ${check.latest_version}`);
                console.log(`   You're on: ${require('../package.json').version}`);
                console.log('   Update: npm install -g reepoe@latest\n');
                // Continue (non-blocking)
            }
            
            return activation.email;
        }
    }
    
    // No valid activation - show activation prompt
    console.log('\n╔═══════════════════════════════════════════════════════════════╗');
    console.log('║  🤖 ReePoe - Activation Required                             ║');
    console.log('╚═══════════════════════════════════════════════════════════════╝\n');
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    
    // Prompt for email
    const email = await new Promise((resolve) => {
        rl.question('📧 Enter your email: ', (answer) => {
            resolve(answer.trim());
        });
    });
    
    if (!email) {
        console.log('\n❌ Email required for activation');
        process.exit(1);
    }
    
    // Prompt for code
    const code = await new Promise((resolve) => {
        rl.question('🔑 Enter activation code (or press Enter to join waitlist): ', (answer) => {
            rl.close();
            resolve(answer.trim());
        });
    });
    
    if (code) {
        // Redeem code
        console.log('\n⏳ Validating activation code...');
        const result = await client.redeemCode(email, code, require('../package.json').version);
        
        if (result.success) {
            console.log('\n╔═══════════════════════════════════════════════════════════════╗');
            console.log('║  ✅ Activation Successful!                                    ║');
            console.log('╚═══════════════════════════════════════════════════════════════╝\n');
            console.log(`Welcome to ReePoe, ${email}!`);
            console.log(`\n📊 Your Account:`);
            console.log(`   Status: Active`);
            console.log(`   Expires: ${new Date(result.user.expires_at).toLocaleDateString()} (30 days)`);
            console.log(`   Type: Alpha tester\n`);
            console.log('💡 Quick Start:');
            console.log('   reepoe query "show me all API endpoints"');
            console.log('   reepoe metrics  - View your stats\n');
            
            return email;
        } else {
            console.log(`\n❌ Activation failed: ${result.message}`);
            if (result.details) {
                console.log(`   ${result.details}`);
            }
            console.log('\n💡 Try joining the waitlist (press Enter when prompted for code)\n');
            process.exit(1);
        }
    } else {
        // Join waitlist
        console.log('\n⏳ Joining waitlist...');
        const result = await client.joinWaitlist(email);
        
        if (result.success) {
            console.log('\n╔═══════════════════════════════════════════════════════════════╗');
            console.log('║  ⏰ Joined Waitlist!                                          ║');
            console.log('╚═══════════════════════════════════════════════════════════════╝\n');
            console.log(`Welcome to the ReePoe waitlist!`);
            console.log(`\n📍 Your Position: #${result.position}`);
            console.log(`📅 Next Code Drop: ${result.next_drop || 'TBD'}`);
            console.log(`\n💡 What Happens Next:`);
            console.log('   - We\'ll email you when a code is available');
            console.log('   - Codes are sent in batches weekly');
            console.log('   - First-come, first-served\n');
            console.log(`❌ ReePoe requires activation to start.`);
            console.log('   You\'ll be notified when your code is ready!\n');
        } else {
            console.log(`\n❌ Failed to join waitlist: ${result.message}\n`);
        }
        
        process.exit(1);
    }
}

// ========== BYOK WIZARD (FIX #1) ==========
async function checkAndSetupBYOK() {
    const byokConfigPath = path.join(os.homedir(), '.reepoe', 'config.json');
    
    if (fs.existsSync(byokConfigPath)) {
        return; // Already configured
    }
    
    const readline = require('readline');
    const crypto = require('crypto');
    
    console.log('\n╔══════════════════════════════════════════════════════════════╗');
    console.log('║      ReePoe BYOK Setup - Bring Your Own Key                 ║');
    console.log('╚══════════════════════════════════════════════════════════════╝\n');
    console.log('💡 ReePoe can use YOUR OpenRouter API key for intelligent routing.');
    console.log('   Benefits:');
    console.log('   ✅ Use OpenRouter free tier (50 queries/day)');
    console.log('   ✅ Full cost transparency and tracking');
    console.log('   ✅ Uses google/gemma-3-4b-it:free for routing\n');
    console.log('   ℹ️  Your key is stored locally and NEVER transmitted.');
    console.log('   ℹ️  Get a free key at: https://openrouter.ai/keys\n');
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    
    const apiKey = await new Promise((resolve) => {
        rl.question('Enter OpenRouter API key (or press Enter to skip): ', (answer) => {
            rl.close();
            resolve(answer.trim());
        });
    });
    
    if (apiKey && apiKey.startsWith('sk-or-v1-')) {
        try {
            const globalConfigDir = path.join(os.homedir(), '.reepoe');
            if (!fs.existsSync(globalConfigDir)) {
                fs.mkdirSync(globalConfigDir, { recursive: true, mode: 0o700 });
            }
            
            const userId = 'anon_' + crypto.createHash('sha256')
                .update(crypto.randomBytes(32))
                .digest('hex')
                .substring(0, 16);
            
            const encryptedKey = Buffer.from(apiKey).toString('base64');
            
            const globalConfig = {
                api_keys: { openrouter: encryptedKey, encrypted: true },
                user_id: userId,
                analytics: { enabled: true, anonymous: true },
                created_at: new Date().toISOString()
            };
            
            fs.writeFileSync(byokConfigPath, JSON.stringify(globalConfig, null, 2), { mode: 0o600 });
            console.log('\n✅ API key stored securely in ~/.reepoe/config.json');
        } catch (error) {
            console.error(`\n❌ Failed to store API key: ${error.message}`);
        }
    } else if (apiKey) {
        console.log('\n⚠️  Invalid key format (should start with sk-or-v1-)');
    } else {
        console.log('\n  ℹ️  Skipping BYOK setup - using default routing');
    }
}

// ========== PROJECT SETUP (FIX #2) ==========
function detectProjectType(projectPath) {
    const markers = {
        'package.json': { language: 'javascript', name: 'Node.js' },
        'requirements.txt': { language: 'python', name: 'Python' },
        'go.mod': { language: 'go', name: 'Go' },
        'Cargo.toml': { language: 'rust', name: 'Rust' },
        'pom.xml': { language: 'java', name: 'Java' }
    };
    
    for (const [file, config] of Object.entries(markers)) {
        if (fs.existsSync(path.join(projectPath, file))) {
            let projectName = path.basename(projectPath);
            
            if (file === 'package.json') {
                try {
                    const pkg = JSON.parse(fs.readFileSync(path.join(projectPath, file), 'utf8'));
                    projectName = pkg.name || projectName;
                    const deps = { ...pkg.dependencies, ...pkg.devDependencies };
                    if (deps.express) config.framework = 'Express';
                    else if (deps.react) config.framework = 'React';
                    else if (deps.vue) config.framework = 'Vue';
                } catch (e) {
                    // Use defaults
                }
            }
            
            return { ...config, projectName };
        }
    }
    
    return { language: 'unknown', name: 'Generic', projectName: path.basename(projectPath) };
}

async function setupProjectIfNeeded(port) {
    const configPath = path.join(process.cwd(), 'reepoe.config.json');
    
    if (fs.existsSync(configPath)) {
        return; // Already set up
    }
    
    console.log('🔍 First run in this directory - initializing project...\n');
    
    const projectInfo = detectProjectType(process.cwd());
    console.log(`   ✅ ${projectInfo.name} project detected`);
    if (projectInfo.framework) {
        console.log(`   Framework: ${projectInfo.framework}`);
    }
    
    const config = {
        project: {
            name: projectInfo.projectName,
            type: projectInfo.language,
            framework: projectInfo.framework || null,
            root: process.cwd()
        },
        api: { port, host: '127.0.0.1' },
        mini_rag: {
            enabled: true,
            confidence_threshold: 0.85,
            cta_whitelist: ['run_tests', 'open_file', 'search_symbols', 'get_repo_stats']
        },
        scanner: { language: projectInfo.language, auto_scan: true }
    };
    
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    console.log(`   ✅ Configuration created`);
    
    ['data', 'logs'].forEach(dir => {
        const dirPath = path.join(process.cwd(), dir);
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }
    });
    console.log(`   ✅ Directories created\n`);
}

// Main function
async function main() {
    // Check activation first (Phase 3B)
    const email = await checkActivationStatus();
    
    // FIX #1: Check and setup BYOK if needed
    await checkAndSetupBYOK();
    
    console.log('\n🚀 Starting ReePoe server...\n');
    
    // Read configuration
    const configPath = path.join(process.cwd(), 'reepoe.config.json');
    let port = 8000;
    
    // FIX #6: Parse CLI arguments for port (priority: CLI > Config > Default)
    const args = process.argv.slice(2);
    const portIndex = args.indexOf('--port');
    let cliPort = null;
    if (portIndex !== -1 && args[portIndex + 1]) {
        cliPort = parseInt(args[portIndex + 1], 10);
    }
    
    if (fs.existsSync(configPath)) {
        try {
            const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
            port = config.api?.port || 8000;
            console.log(`📋 Configuration found: ${configPath}`);
        } catch (e) {
            console.log('⚠️  Using default configuration');
        }
    } else {
        console.log('ℹ️  No configuration found, using defaults');
    }
    
    // Apply CLI override
    if (cliPort) {
        port = cliPort;
        console.log(`👉 Using port ${port} from command line`);
    }
    
    // Detect cloud environment
    const isCloud = isCloudEnvironment();
    
    // FIX #2: Setup project if needed (before starting binary)
    if (!isCloud) {
        await setupProjectIfNeeded(port);
    }
    
    if (isCloud) {
        // Cloud environment - skip local server
        console.log('\n☁️  Cloud environment detected');
        console.log('📡 Using production ReePoe API: https://reepoe-api.onrender.com\n');
        console.log('✅ Ready to use!');
        console.log('\n💡 Try:');
        console.log('   reepoe query "test query"\n');
        return;
    }
    
    // Check if already running
    const running = await isServerRunning(port);
    if (running) {
        console.log(`\n✅ ReePoe is already running on port ${port}`);
        console.log(`   API: http://localhost:${port}`);
        console.log(`   Dashboard: http://localhost:${port}/dashboard`);
        return;
    }
    
    // Get binary path
    const binaryPath = getBinaryPath();
    
    if (!binaryPath) {
        console.error(`❌ ReePoe binary not found for ${os.platform()}-${os.arch()}`);
        console.error('   Try reinstalling: npm install -g reepoe');
        process.exit(1);
    }
    
    // Start server
    console.log(`🔧 Starting server on port ${port}...`);
    
    const env = {
        ...process.env,
        PORT: port.toString(),
        HOST: '127.0.0.1',
        PYTHONUNBUFFERED: '1',
        REEPOE_PROJECT_ROOT: process.cwd()  // Phase 1: Pass user's directory to server
    };
    
    const child = spawn(binaryPath, [], {
        env,
        detached: true,
        stdio: 'ignore',
        cwd: process.cwd()
    });
    
    child.unref();
    
    // Store PID
    const pidFile = path.join(os.tmpdir(), `reepoe-${port}.pid`);
    fs.writeFileSync(pidFile, child.pid.toString());
    
    // Wait for server to start with retry loop (FIX: More robust startup detection)
    console.log('   Waiting for server to initialize...');
    
    let started = false;
    const maxRetries = 15;  // 15 retries * 2 seconds = 30 seconds max
    const retryInterval = 2000;  // 2 seconds between retries
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
        await new Promise(resolve => setTimeout(resolve, retryInterval));
        
        started = await isServerRunning(port);
        if (started) {
            break;
        }
        
        // Show progress dots for user feedback
        if (attempt % 3 === 0) {
            process.stdout.write('.');
        }
    }
    
    if (started) {
        console.log(`\n✅ ReePoe server started successfully!`);
        console.log(`\n📡 Endpoints:`);
        console.log(`   API: http://localhost:${port}`);
        console.log(`   Health: http://localhost:${port}/health`);
        console.log(`   Metrics: http://localhost:${port}/metrics`);
        console.log(`   Describe: http://localhost:${port}/describe`);
        console.log(`\n💡 Try: reepoe query "what does this codebase do?"`);
        console.log(`   Stop: reepoe-stop\n`);
    } else {
        // Server might still be starting - don't exit, just warn
        console.log(`\n⏳ Server startup is taking longer than expected...`);
        console.log(`   The server may still be indexing your codebase.`);
        console.log(`\n💡 Check status: reepoe-status`);
        console.log(`   If server is running: curl http://localhost:${port}/health`);
        console.log(`   View logs: ${path.join(process.cwd(), 'logs', 'server.log')}`);
        // Do NOT exit(1) - server is likely still starting
    }
}

main().catch(error => {
    console.error(`❌ Error: ${error.message}`);
    process.exit(1);
});

