#!/usr/bin/env node
/**
 * ReePoe Stop - Stops ReePoe server
 */

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

function main() {
    console.log('\n🛑 Stopping ReePoe server...\n');
    
    // Read configuration to get port
    const configPath = path.join(process.cwd(), 'reepoe.config.json');
    let port = 8000;
    
    if (fs.existsSync(configPath)) {
        try {
            const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
            port = config.api?.port || 8000;
        } catch (e) {
            // Use default
        }
    }
    
    // Find PID file
    const pidFile = path.join(os.tmpdir(), `reepoe-${port}.pid`);
    
    if (!fs.existsSync(pidFile)) {
        console.log('ℹ️  ReePoe server doesn\'t appear to be running (no PID file found)');
        return;
    }
    
    // Read PID
    const pid = parseInt(fs.readFileSync(pidFile, 'utf8'));
    
    // Kill process
    try {
        process.kill(pid, 'SIGTERM');
        fs.unlinkSync(pidFile);
        console.log(`✅ ReePoe server stopped (PID: ${pid})`);
        console.log(`   Port ${port} is now available\n`);
    } catch (error) {
        if (error.code === 'ESRCH') {
            console.log('ℹ️  Process not found (may have already stopped)');
            fs.unlinkSync(pidFile);
        } else {
            console.error(`❌ Failed to stop server: ${error.message}`);
            process.exit(1);
        }
    }
}

main();

