import { WebSocketServer } from 'ws';
import { spawn } from 'child_process';

const PORT = 7701;
const wss = new WebSocketServer({ port: PORT });
console.log(`Terminal WS server on ws://localhost:${PORT}`);

wss.on('connection', (ws) => {
  const shell = spawn('/bin/bash', [], {
    env: { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor' },
    cwd: process.env.HOME || '/root',
  });

  shell.stdout.on('data', (d) => { try { ws.send(JSON.stringify({ type:'data', data: d.toString('binary') })); } catch{} });
  shell.stderr.on('data', (d) => { try { ws.send(JSON.stringify({ type:'data', data: d.toString('binary') })); } catch{} });
  shell.on('close', (code) => { try { ws.send(JSON.stringify({ type:'exit', code })); ws.close(); } catch{} });

  ws.on('message', (msg) => {
    try {
      const m = JSON.parse(msg.toString());
      if (m.type === 'input') shell.stdin.write(m.data);
      if (m.type === 'resize') { /* no node-pty resize without pty, best effort */ }
    } catch{}
  });

  ws.on('close', () => { shell.kill(); });
});
