const express = require('express');
const router = express.Router();
const pm = require('../services/project-manager');
const fs = require('fs');

router.get('/', (req, res) => {
  const projects = pm.getAll();
  res.render('projects', { projects });
});

router.get('/add', (req, res) => {
  res.render('project-add');
});

router.post('/add', (req, res) => {
  const { name, path } = req.body;
  if (!name || !path || !fs.existsSync(path)) {
    return res.render('project-add', { error: 'Invalid project path or name' });
  }
  const project = pm.add(name, path);
  res.redirect(`/projects/${project.id}`);
});

router.get('/:id', (req, res) => {
  const project = pm.get(req.params.id);
  if (!project) return res.status(404).render('error', { message: 'Project not found' });

  const bridge = pm.getBridge(req.params.id);
  const statusResult = bridge.status();
  const list = bridge.listAll();

  res.render('project', { project, status: statusResult, list });
});

router.post('/:id/remove', (req, res) => {
  pm.remove(req.params.id);
  res.redirect('/projects');
});

router.post('/:id/run-pipeline', (req, res) => {
  const project = pm.get(req.params.id);
  if (!project) return res.status(404).json({ error: 'Project not found' });

  const bridge = pm.getBridge(req.params.id);
  const { storyName } = req.body;

  let result;
  if (storyName) {
    result = bridge.runFull(storyName);
  } else {
    result = bridge.status();
  }

  res.json({ success: result.success, output: result.output, error: result.error });
});

router.post('/:id/execute', (req, res) => {
  const project = pm.get(req.params.id);
  if (!project) return res.status(404).json({ error: 'Project not found' });

  const bridge = pm.getBridge(req.params.id);
  const { testName } = req.body;
  const result = bridge.execute(testName);
  res.json({ success: result.success, output: result.output, error: result.error, runId: extractRunId(result.output) });
});

router.post('/:id/heal', (req, res) => {
  const project = pm.get(req.params.id);
  if (!project) return res.status(404).json({ error: 'Project not found' });

  const bridge = pm.getBridge(req.params.id);
  const { runId } = req.body;
  const result = bridge.heal(runId);
  res.json({ success: result.success, output: result.output, error: result.error });
});

router.post('/:id/report', (req, res) => {
  const project = pm.get(req.params.id);
  if (!project) return res.status(404).json({ error: 'Project not found' });

  const bridge = pm.getBridge(req.params.id);
  const { runId } = req.body;
  const result = bridge.report(runId);
  res.json({ success: result.success, output: result.output, error: result.error });
});

function extractRunId(output) {
  const match = output.match(/run-[\d-T-]+/);
  return match ? match[0] : null;
}

module.exports = router;
