const express = require('express');
const router = express.Router();
const pm = require('../services/project-manager');
const { spawn } = require('child_process');

router.get('/', (req, res) => {
  const projects = pm.getAll();
  const projectId = req.query.project || (projects.length > 0 ? projects[0].id : null);
  const project = projects.find(p => p.id === projectId);
  res.render('terminal', { project, projects });
});

// Execute a command asynchronously with streaming output
router.post('/run', (req, res) => {
  const projects = pm.getAll();
  const projectId = req.query.project || (projects.length > 0 ? projects[0].id : null);
  const project = projects.find(p => p.id === projectId);
  if (!project) return res.status(404).send('Project not found');

  const { command } = req.body;
  if (!command) return res.status(400).send('No command provided');

  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.setHeader('Transfer-Encoding', 'chunked');
  res.setHeader('X-Content-Type-Options', 'nosniff');

  const child = spawn(command, [], {
    cwd: project.path,
    shell: true,
    env: { ...process.env, FORCE_COLOR: '0' },
  });

  child.stdout.on('data', (data) => res.write(data.toString()));
  child.stderr.on('data', (data) => res.write(data.toString()));

  child.on('close', (code) => {
    res.write(`\n\n--- [FINISHED: ${code === 0 ? 'SUCCESS' : 'FAILED'}] (exit code: ${code}) ---\n`);
    res.end();
  });

  child.on('error', (err) => {
    res.write(`\nError: ${err.message}\n`);
    res.end();
  });

  req.on('close', () => {
    if (child && !child.killed) child.kill('SIGINT');
  });
});

module.exports = router;