#!/usr/bin/env node
/**
 * ReePoe Status - Check ReePoe server status
 */

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

async function checkServerHealth(port) {
    try {
        const response = await axios.get(`http://localhost:${port}/health`, { timeout: 2000 });
        return { running: true, healthy: true, data: response.data };
    } catch (error) {
        if (error.code === 'ECONNREFUSED') {
            return { running: false, healthy: false };
        }
        return { running: true, healthy: false, error: error.message };
    }
}

async function main() {
    console.log('\n📊 ReePoe Server Status\n');
    
    // Read configuration
    const configPath = path.join(process.cwd(), 'reepoe.config.json');
    let port = 8000;
    let projectName = 'unknown';
    
    if (fs.existsSync(configPath)) {
        try {
            const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
            port = config.api?.port || 8000;
            projectName = config.project?.name || path.basename(process.cwd());
            console.log(`📁 Project: ${projectName}`);
            console.log(`🔧 Configuration: ${configPath}`);
        } catch (e) {
            console.log('⚠️  Configuration file exists but couldn\'t be read');
        }
    } else {
        console.log('ℹ️  No configuration file found');
    }
    
    console.log(`🌐 Expected port: ${port}`);
    
    // Check PID file
    const pidFile = path.join(os.tmpdir(), `reepoe-${port}.pid`);
    let pid = null;
    
    if (fs.existsSync(pidFile)) {
        pid = parseInt(fs.readFileSync(pidFile, 'utf8'));
        console.log(`📝 PID file found: ${pid}`);
    } else {
        console.log(`📝 No PID file found`);
    }
    
    // Check server health
    console.log(`\n🏥 Health check: http://localhost:${port}/health`);
    const health = await checkServerHealth(port);
    
    if (health.running && health.healthy) {
        console.log(`✅ Server is RUNNING and HEALTHY`);
        console.log(`\n📡 Available endpoints:`);
        console.log(`   - GET  http://localhost:${port}/describe`);
        console.log(`   - POST http://localhost:${port}/query`);
        console.log(`   - GET  http://localhost:${port}/metrics`);
        console.log(`\n💡 Try: reepoe query "what does this codebase do?"`);
    } else if (health.running && !health.healthy) {
        console.log(`⚠️  Server is running but unhealthy`);
        console.log(`   Error: ${health.error}`);
    } else {
        console.log(`❌ Server is NOT RUNNING`);
        console.log(`\n💡 Start it with: reepoe-start`);
    }
    
    console.log('');
}

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

