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

const app = express();
const PORT = 9999;

app.use(express.static(path.join(__dirname, 'public')));

app.get('/api/logs', (req, res) => {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders();

    const service = req.query.service || 'curio-app';
    let label = 'app=curio-app';
    if (service === 'curaflow-agent') {
        label = 'app.kubernetes.io/name=curaflow-agent';
    }

    // Spawn kubectl logs
    const kubectl = spawn('kubectl', ['logs', '-f', '-n', 'curio', '-l', label, '--tail=100']);

    kubectl.stdout.on('data', (data) => {
        const lines = data.toString().split('\n');
        lines.forEach(line => {
            if (line.trim()) {
                res.write(`data: ${JSON.stringify({ text: line, isError: false })}\n\n`);
            }
        });
    });

    kubectl.stderr.on('data', (data) => {
        const lines = data.toString().split('\n');
        lines.forEach(line => {
            if (line.trim()) {
                res.write(`data: ${JSON.stringify({ text: line, isError: true })}\n\n`);
            }
        });
    });

    kubectl.on('close', (code) => {
        res.write(`data: ${JSON.stringify({ text: `[Process exited with code ${code}]`, isError: true })}\n\n`);
        res.end();
    });

    req.on('close', () => {
        kubectl.kill();
    });
});

app.listen(PORT, () => {
    console.log(`Curio Log Viewer running at http://localhost:${PORT}`);
});
