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

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

  const project = projects.length > 0 ? projects[0] : null;

  let stats = {
    stories: 0,
    plans: 0,
    specs: 0,
    runs: 0,
    passedRuns: 0,
    passRate: 0,
    lastRunStatus: null,
    storiesList: [],
    latestRun: null,
    hasAllure: false,
  };

  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;
    stats.hasAllure = bridge.hasAllureReport();

    stats.storiesList = list.stories.map(s => {
      const baseName = s.replace(/\.md$/i, '');
      return {
        name: s,
        hasPlan: list.plans.some(p => p.toLowerCase().includes(baseName.toLowerCase())),
        planName: list.plans.find(p => p.toLowerCase().includes(baseName.toLowerCase())),
        hasSpec: list.specs.some(sp => sp.toLowerCase().includes(baseName.toLowerCase())),
        specName: list.specs.find(sp => sp.toLowerCase().includes(baseName.toLowerCase())),
      };
    });

    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;

      const latest = bridge.getRunResult(runDirs[0].name);
      if (latest) {
        stats.lastRunStatus = latest.success ? 'passed' : 'failed';
        stats.latestRun = {
          id: runDirs[0].name,
          duration: latest.duration,
          passedCount: latest.passedTests ? latest.passedTests.length : 0,
          failedCount: latest.failedTests ? latest.failedTests.length : 0,
          testName: latest.test,
        };
      }
    }
  }

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

module.exports = router;
