'use strict';
require('dotenv').config();
const express = require('express');
const cors    = require('cors');
const path    = require('path');
const fs      = require('fs');

const { getConfig, countTests }    = require('./db');
const { fullScan }     = require('./scanner');
const { startWatching } = require('./watcher')

const app  = express();
const PORT = process.env.PORT || 3001;

app.use(cors());
app.use(express.json());

// ── API routes ──────────────────────────────────────────────────────────────
app.use('/api/tests',  require('./routes/tests'));
app.use('/api/stats',  require('./routes/stats'));
app.use('/api/config', require('./routes/config'));
app.use('/api/browse', require('./routes/browse'));
app.use('/api/events', require('./routes/events'));

// ── Serve built React frontend in production ────────────────────────────────
const distPath = path.resolve(__dirname, '../dashboard/dist');
if (fs.existsSync(distPath)) {
  app.use(express.static(distPath));
  app.get('*', (req, res) => res.sendFile(path.join(distPath, 'index.html')));
}

// ── Start ───────────────────────────────────────────────────────────────────
async function start() {
  const targetDir  = getConfig('target_dir');
  const resultsDir = getConfig('results_dir');

  if (targetDir && resultsDir) {
    const existing = countTests();
    if (existing > 0) {
      console.log(`[server] Resuming from DB — ${existing} tests already loaded.`);
    } else {
      console.log('[server] No cached data, scanning directories...');
      await fullScan(targetDir, resultsDir);
      const { getAllTests } = require('./db');
      const tests = getAllTests();
      console.log(`[server] Scan complete — ${tests.length} tests found, ${tests.filter(t => t.completed).length} completed`);
    }
    startWatching(targetDir, resultsDir);
    console.log('[server] Watching for changes.');
  } else {
    console.log('[server] No directories configured — open the dashboard settings to get started.');
  }

  app.listen(PORT, '0.0.0.0', () => {
    console.log(`[server] Listening on http://0.0.0.0:${PORT}`);
  });
}

start().catch(console.error);
