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

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);

  if (!project || !pm.getBridge(projectId)) {
    return res.render('analytics', { project: null, projects, runs: [], stats: { totalRuns: 0, passedRuns: 0, totalFailures: 0, totalHealed: 0, totalDefects: 0, avgDuration: 0, passRate: 0, healRate: 0 } });
  }

  const bridge = pm.getBridge(project.id);
  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,
      total: result && result.failedTests ? result.failedTests.length + (result.passedTests ? result.passedTests.length : 0) : 0,
      failures: result && result.failedTests ? result.failedTests.length : 0,
      healed: healing ? healing.totalHealed || 0 : 0,
      defects: healing && healing.defects ? healing.defects.length : 0,
      testName: result ? result.test : 'N/A',
    };
  });

  const totalRuns = runs.length;
  const passedRuns = runs.filter(r => r.success).length;
  const totalFailures = runs.reduce((s, r) => s + r.failures, 0);
  const totalHealed = runs.reduce((s, r) => s + r.healed, 0);
  const totalDefects = runs.reduce((s, r) => s + r.defects, 0);
  const avgDuration = runs.length > 0 ? (runs.reduce((s, r) => s + (r.duration || 0), 0) / runs.length) : 0;
  const passRate = totalRuns > 0 ? ((passedRuns / totalRuns) * 100).toFixed(1) : 0;
  const healRate = totalFailures > 0 ? ((totalHealed / totalFailures) * 100).toFixed(1) : 0;

  res.render('analytics', {
    project,
    projects,
    runs: runs.reverse(),
    stats: { totalRuns, passedRuns, totalFailures, totalHealed, totalDefects, avgDuration, passRate, healRate },
  });
});

module.exports = router;
