#!/usr/bin/env node
/**
 * ReePoe Post-Install Setup
 * Automatically configures ReePoe for the current project
 */

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

// Detect project type
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))) {
            // Read project name if possible
            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;
                    
                    // Detect framework
                    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) };
}

// Find available port
async function findAvailablePort(start = 8000, end = 9000) {
    const net = require('net');
    
    for (let port = start; port <= end; port++) {
        const available = await new Promise((resolve) => {
            const server = net.createServer();
            server.once('error', () => resolve(false));
            server.once('listening', () => {
                server.close();
                resolve(true);
            });
            server.listen(port, '127.0.0.1');
        });
        
        if (available) {
            return port;
        }
    }
    
    return start; // Fallback to first port
}

// Create configuration file
async function createConfiguration(projectInfo, port) {
    const config = {
        project: {
            name: projectInfo.projectName,
            type: projectInfo.language,
            framework: projectInfo.framework || null,
            root: process.cwd()
        },
        api: {
            port: port,
            host: '127.0.0.1'
        },
        mini_rag: {
            enabled: true,
            confidence_threshold: 0.6,
            cta_whitelist: ['run_tests', 'open_file', 'search_symbols', 'get_repo_stats']
        },
        scanner: {
            language: projectInfo.language,
            auto_scan: true
        }
    };
    
    const configPath = path.join(process.cwd(), 'reepoe.config.json');
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    
    return configPath;
}

// Create data directories
function createDataDirectories() {
    const dirs = ['data', 'logs'];
    
    for (const dir of dirs) {
        const dirPath = path.join(process.cwd(), dir);
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }
    }
}

// ========== BYOK (Bring Your Own Key) Setup Wizard ==========

async function setupBYOK() {
    // BYOK Setup Wizard for global installations
    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');
    
    // Prompt for API key
    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.length > 0) {
        // Validate format
        if (apiKey.startsWith('sk-or-v1-')) {
            try {
                // Store API key in ~/.reepoe/config.json
                const globalConfigDir = path.join(os.homedir(), '.reepoe');
                const globalConfigPath = path.join(globalConfigDir, 'config.json');
                
                // Create directory if doesn't exist
                if (!fs.existsSync(globalConfigDir)) {
                    fs.mkdirSync(globalConfigDir, { recursive: true, mode: 0o700 });
                }
                
                // Generate anonymous user ID
                const userId = 'anon_' + crypto.createHash('sha256')
                    .update(crypto.randomBytes(32))
                    .digest('hex')
                    .substring(0, 16);
                
                // Simple encryption (base64)
                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(globalConfigPath, JSON.stringify(globalConfig, null, 2), { mode: 0o600 });
                
                console.log('\n✅ API key stored securely in ~/.reepoe/config.json');
                console.log('   Your key is encrypted and only accessible by you.');
                console.log('   Anonymous user ID generated for analytics.');
                console.log('\n💰 Cost tracking enabled - monitor your usage in real-time!');
                
            } catch (error) {
                console.error(`\n❌ Failed to store API key: ${error.message}`);
                console.log('   Continuing with limited features...');
            }
        } else {
            console.log('\n⚠️  Invalid API key format (should start with sk-or-v1-)');
            console.log('   Skipping BYOK setup - ReePoe will use default routing.');
            console.log('   You can add your key later in ~/.reepoe/config.json');
        }
    } else {
        console.log('\n  ℹ️  Skipping BYOK setup - using default routing');
        console.log('   ReePoe will work with limited features.');
        console.log('   To enable BYOK later, run: reepoe-setup-key');
    }
}

// Main setup function
async function setup() {
    // For global install, run BYOK wizard
    if (process.env.npm_config_global === 'true') {
        await setupBYOK();
        
        console.log('\n✅ ReePoe installed globally');
        console.log('\n📝 To use in a project:');
        console.log('   cd /path/to/your/project');
        console.log('   reepoe-start\n');
        return;
    }
    
    console.log('\n╔══════════════════════════════════════════════════════════════╗');
    console.log('║           ReePoe Plugin - Auto Setup                        ║');
    console.log('╚══════════════════════════════════════════════════════════════╝\n');
    
    // Detect project
    console.log('🔍 Detecting project type...');
    const projectInfo = detectProjectType(process.cwd());
    console.log(`   ✅ ${projectInfo.name} project detected`);
    if (projectInfo.framework) {
        console.log(`   Framework: ${projectInfo.framework}`);
    }
    
    // Find available port
    console.log('\n⚙️  Finding available port...');
    const port = await findAvailablePort();
    console.log(`   ✅ Port ${port} available`);
    
    // Create configuration
    console.log('\n📝 Creating configuration...');
    const configPath = await createConfiguration(projectInfo, port);
    console.log(`   ✅ Configuration created: ${configPath}`);
    
    // Create directories
    console.log('\n📁 Setting up directories...');
    createDataDirectories();
    console.log(`   ✅ Data directories created`);
    
    // Success message
    console.log('\n╔══════════════════════════════════════════════════════════════╗');
    console.log('║              ✅ ReePoe Setup Complete!                       ║');
    console.log('╚══════════════════════════════════════════════════════════════╝\n');
    
    console.log('🚀 Start ReePoe:');
    console.log('   reepoe-start\n');
    
    console.log('💡 Try these commands:');
    console.log('   reepoe query "what does this codebase do?"');
    console.log('   reepoe query "show me all API endpoints"');
    console.log('   reepoe query "find test files"\n');
    
    console.log('📊 Management:');
    console.log('   reepoe-status  - Check server status');
    console.log('   reepoe-stop    - Stop server\n');
}

setup().catch(error => {
    console.error(`\n❌ Setup failed: ${error.message}`);
    console.error('   You can run setup manually with: node scripts/setup.js');
    process.exit(1);
});

