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

router.get('/', (req, res) => {
  const projectId = req.query.project;
  const project = projectId ? pm.get(projectId) : pm.getAll()[0];
  if (!project) return res.redirect('/projects');

  const bridge = pm.getBridge(project.id);
  const allFiles = bridge.listAll();
  const runDirs = bridge.getRunDirs();

  const runs = runDirs.map(d => {
    const result = bridge.getRunResult(d.name);
    const healing = bridge.getHealingReport(d.name);
    return {
      id: d.name,
      timestamp: d.name.replace('run-', '').replace(/-/g, ':').slice(0, 19),
      success: result ? result.success : null,
      duration: result ? result.duration : null,
      testName: result ? result.test : 'Unknown',
      failedCount: result && Array.isArray(result.failedTests) ? result.failedTests.length : 0,
      passedCount: result && Array.isArray(result.passedTests) ? result.passedTests.length : 0,
      healedCount: healing ? healing.totalHealed || 0 : 0,
      hasReport: !!bridge.getFinalReport(d.name),
    };
  });

  const latestRun = runs.length > 0 ? runs[0] : null;

  const allDefects = [];
  for (const d of runDirs) {
    const result = bridge.getRunResult(d.name);
    if (result && Array.isArray(result.failedTests)) {
      for (const ft of result.failedTests) {
        allDefects.push({
          runId: d.name,
          testName: typeof ft === 'string' ? ft : (ft.name || ft.test || 'Unknown'),
          error: typeof ft === 'string' ? '' : (ft.error || ft.message || ''),
          runTimestamp: d.name.replace('run-', '').replace(/-/g, ':').slice(0, 19),
        });
      }
    }
  }

  const totalPassed = runs.reduce((s, r) => s + r.passedCount, 0);
  const totalFailed = runs.reduce((s, r) => s + r.failedCount, 0);
  const totalHealed = runs.reduce((s, r) => s + r.healedCount, 0);
  const totalRuns = runs.length;

  res.render('review', {
    project,
    stats: {
      stories: allFiles.stories.length,
      plans: allFiles.plans.length,
      specs: allFiles.specs.length,
      runs: totalRuns,
      passed: totalPassed,
      failed: totalFailed,
      healed: totalHealed,
    },
    latestRun,
    runs,
    defects: allDefects,
  });
});

router.get('/:runId', (req, res) => {
  const projectId = req.query.project;
  const project = projectId ? pm.get(projectId) : pm.getAll()[0];
  if (!project) return res.redirect('/projects');

  const bridge = pm.getBridge(project.id);
  const runDirs = bridge.getRunDirs();
  const runExists = runDirs.some(d => d.name === req.params.runId);
  if (!runExists) return res.status(404).render('error', { message: 'Review: run not found' });

  let result = bridge.getRunResult(req.params.runId);
  if (!result) {
    const outputPath = path.join(bridge.projectPath, 'test-results', req.params.runId, 'execution-output.json');
    let outputText = 'No console output captured yet.';
    if (fs.existsSync(outputPath)) {
      try { outputText = fs.readFileSync(outputPath, 'utf-8'); } catch (err) {}
    }
    result = {
      runId: req.params.runId,
      success: null,
      duration: null,
      test: 'Running / In Progress...',
      timestamp: new Date().toISOString(),
      failedTests: [],
      passedTests: [],
      output: outputText,
    };
  }

  const healing = bridge.getHealingReport(req.params.runId);
  const report = bridge.getFinalReport(req.params.runId);

  res.render('review', {
    project,
    run: {
      id: req.params.runId,
      result,
      healing,
      report,
    },
  });
});

module.exports = router;
