const chokidar = require('chokidar');
const path = require('path');

function startWatcher({ inputFile, inputDir, server }) {
  const isDir = !!inputDir;
  // Watch the directory or the single file
  const watchTarget = isDir ? path.resolve(inputDir) : path.resolve(inputFile);

  const watcher = chokidar.watch(watchTarget, {
    persistent: true,
    ignoreInitial: true,
    ignored: /(^|[/\\])\.\./, // ignore hidden files
    usePolling: true,
    interval: 300,
    awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 50 },
  });

  let debounceTimer = null;

  function isMd(filePath) {
    return /\.md$/i.test(filePath);
  }

  function schedule(filePath) {
    // In dir mode, only react to .md files
    if (isDir && filePath && !isMd(filePath)) return;
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      server.rebuild(filePath);
    }, 80);
  }

  watcher.on('change', schedule);
  watcher.on('add', (filePath) => {
    if (!isDir || isMd(filePath)) {
      console.log(`  +  Nouveau fichier : ${path.basename(filePath)}`);
      schedule(null); // file list changed → full cache invalidation
    }
  });
  watcher.on('unlink', (filePath) => {
    if (!isDir || isMd(filePath)) {
      console.log(`  -  Supprimé : ${path.basename(filePath)}`);
      schedule(null);
    }
  });

  // Re-watch single file if recreated via temp+rename (some editors)
  if (!isDir) {
    watcher.on('unlink', () => {
      setTimeout(() => watcher.add(path.resolve(inputFile)), 300);
    });
  }

  process.on('SIGINT', () => {
    watcher.close();
    server.server.close();
    console.log('\n👋  Au revoir !');
    process.exit(0);
  });
}

module.exports = { startWatcher };
