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

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

  // Single-project mode: always use the first (and only) registered project
  const project = projects.length > 0 ? projects[0] : null;

  let stats = {
    stories: 0,
    plans: 0,
    specs: 0,
    runs: 0,
    passedRuns: 0,
    passRate: 0,
    lastRunStatus: null, // 'passed' | 'failed' | null
  };

  if (project) {
    const bridge = pm.getBridge(project.id);
    const list = bridge.listAll();
    const runDirs = bridge.getRunDirs();

    stats.stories = list.stories.length;
    stats.plans   = list.plans.length;
    stats.specs   = list.specs.length;
    stats.runs    = runDirs.length;

    if (runDirs.length > 0) {
      const results = runDirs.map(d => bridge.getRunResult(d.name)).filter(Boolean);
      stats.passedRuns = results.filter(r => r.success).length;
      stats.passRate   = results.length > 0
        ? Math.round((stats.passedRuns / results.length) * 100)
        : 0;

      // Most recent run result
      const latest = bridge.getRunResult(runDirs[0].name);
      if (latest) stats.lastRunStatus = latest.success ? 'passed' : 'failed';
    }
  }

  res.render('index', { projects, project, stats });
});

module.exports = router;
