const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');

const LOG = path.join(__dirname, 'data', 'bot.log');
const PORT = process.env.PORT || 8090;

const wss = new WebSocket.Server({ port: PORT });
console.log('WS server running at ws://localhost:' + PORT);

// Funktion til at hente de sidste n linjer fra logfilen
function tail(n = 80) {
  try {
    const t = fs.readFileSync(LOG, 'utf8');
    const L = t.split('\n');
    return L.slice(-n).join('\n');
  } catch (e) {
    return '';
  }
}

// Send seneste log ved ny forbindelse
wss.on('connection', ws => {
  ws.send(JSON.stringify({
    type: 'log',
    data: tail(80)
  }));
});

// Tjek for ændringer i logfilen og broadcast
let last = '';
setInterval(() => {
  const t = tail(80);
  if (t !== last) {
    const payload = JSON.stringify({ type: 'log', data: t });
    wss.clients.forEach(c => {
      if (c.readyState === WebSocket.OPEN) c.send(payload);
    });
    last = t;
  }
}, 500);
