const http = require('http');
const fs = require('fs');
const path = require('path');
const { convert, buildIndex } = require('./converter');

const MIME_TYPES = {
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.svg': 'image/svg+xml',
  '.webp': 'image/webp',
  '.css': 'text/css',
  '.js': 'application/javascript',
  '.ico': 'image/x-icon',
};

/** Recursively find all .md files under a directory. */
function findMarkdownFiles(dir) {
  const results = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (entry.name.startsWith('.')) continue;
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      results.push(...findMarkdownFiles(full));
    } else if (/\.md$/i.test(entry.name)) {
      results.push(full);
    }
  }
  return results;
}

function notifyClients(clients) {
  const dead = [];
  clients.forEach((res) => {
    try {
      res.write('data: reload\n\n');
    } catch {
      dead.push(res);
    }
  });
  return clients.filter((c) => !dead.includes(c) && !c.writableEnded);
}

function startServer({ inputFile, inputDir, port, onReady }) {
  let clients = [];
  const isDir = !!inputDir;
  const baseDir = isDir ? path.resolve(inputDir) : path.dirname(path.resolve(inputFile));

  // --- cache ---
  // pageCache: filePath → rendered HTML string
  // fileListCache: cached list of all .md files (null = stale)
  const pageCache = new Map();
  let fileListCache = null;

  function getCachedFiles() {
    if (!fileListCache) fileListCache = findMarkdownFiles(baseDir);
    return fileListCache;
  }

  // --- rebuild ---
  function rebuild(changedFile) {
    if (changedFile) {
      const rel = path.relative(baseDir, changedFile);
      console.log(`  ↺  ${rel} — rechargement...`);
      // Only this page's HTML is stale; other pages' sidebars are still valid
      pageCache.delete(changedFile);
    } else {
      // File added or removed: file list changed → all caches stale
      pageCache.clear();
      fileListCache = null;
    }
    clients = notifyClients(clients);
  }

  // --- request handler ---
  const server = http.createServer((req, res) => {
    const url = new URL(req.url, `http://localhost:${port}`);
    const pathname = decodeURIComponent(url.pathname);

    // SSE endpoint
    if (pathname === '/events') {
      res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        'X-Accel-Buffering': 'no',
      });
      if (req.socket) req.socket.setNoDelay(true);
      res.write(': keep-alive\n\n');
      clients.push(res);

      const heartbeat = setInterval(() => {
        if (res.writableEnded) { clearInterval(heartbeat); return; }
        res.write(': ping\n\n');
      }, 15000);

      req.on('close', () => {
        clearInterval(heartbeat);
        clients = clients.filter((c) => c !== res);
      });
      return;
    }

    // ── SINGLE FILE MODE ──────────────────────────────────────────────────────
    if (!isDir) {
      if (pathname === '/' || pathname === '/index.html') {
        if (!pageCache.has(inputFile)) {
          pageCache.set(inputFile, convert(inputFile, true));
        }
        res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
        res.end(pageCache.get(inputFile));
        return;
      }
      return serveStatic(req, res, pathname, baseDir, port);
    }

    // ── DIRECTORY MODE ────────────────────────────────────────────────────────

    // Index page
    if (pathname === '/') {
      const files = getCachedFiles();
      // Redirect to Home.md if it exists
      const homePage = files.find((f) =>
        /^home\.md$/i.test(path.basename(f)) && path.dirname(f) === baseDir
      );
      if (homePage) {
        const slug = path.relative(baseDir, homePage).replace(/\.md$/i, '');
        res.writeHead(302, { Location: '/' + slug.split('/').map(encodeURIComponent).join('/') });
        res.end();
        return;
      }
      const indexKey = '__index__';
      if (!pageCache.has(indexKey)) {
        pageCache.set(indexKey, buildIndex(baseDir, files, true));
      }
      res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
      res.end(pageCache.get(indexKey));
      return;
    }

    // Try to serve a markdown page: /Some-Page → Some-Page.md
    const pagePath = pathname.replace(/^\//, '');
    const candidates = [
      path.join(baseDir, pagePath + '.md'),
      path.join(baseDir, pagePath + '.MD'),
      path.join(baseDir, pagePath),           // already has extension
      path.join(baseDir, pagePath, 'index.md'),
    ];

    for (const candidate of candidates) {
      // Security: block path traversal
      if (!candidate.startsWith(baseDir + path.sep) && candidate !== baseDir) continue;
      if (fs.existsSync(candidate) && /\.md$/i.test(candidate)) {
        try {
          if (!pageCache.has(candidate)) {
            const files = getCachedFiles();
            pageCache.set(candidate, convert(candidate, true, { baseDir, files }));
          }
          res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
          res.end(pageCache.get(candidate));
        } catch (err) {
          res.writeHead(500);
          res.end(`Erreur de conversion : ${err.message}`);
        }
        return;
      }
    }

    // Fall back to serving a static asset
    serveStatic(req, res, pathname, baseDir, port);
  });

  function warmCache() {
    const files = getCachedFiles();
    let count = 0;
    if (isDir) {
      for (const file of files) {
        if (!pageCache.has(file)) {
          try {
            pageCache.set(file, convert(file, true, { baseDir, files }));
            count++;
          } catch { /* ignore errors on warm-up */ }
        }
      }
    } else {
      if (!pageCache.has(inputFile)) {
        try {
          pageCache.set(inputFile, convert(inputFile, true));
          count++;
        } catch { /* ignore */ }
      }
    }
    if (count > 0) console.log(`🔥  Cache préchauffé : ${count} page(s) prête(s)\n`);
  }

  server.listen(port, () => {
    console.log(`\n🚀  Serveur démarré : http://localhost:${port}`);
    if (isDir) {
      console.log(`📂  Dossier         : ${baseDir}`);
    }
    if (onReady) {
      onReady(port);
    } else {
      console.log('👁   Surveillance des modifications... (Ctrl+C pour arrêter)');
    }
    // Pre-render all pages so first visits are instant
    setImmediate(warmCache);
  });

  server.on('error', (err) => {
    if (err.code === 'EADDRINUSE') {
      console.error(`\n✗ Erreur : le port ${port} est déjà utilisé. Essayez --port <autre>`);
      process.exit(1);
    }
    throw err;
  });

  return { server, rebuild };
}

function serveStatic(req, res, pathname, baseDir, port) {
  const safePath = path.normalize(pathname).replace(/^(\.\.[/\\])+/, '');
  const filePath = path.join(baseDir, safePath);

  if (!filePath.startsWith(baseDir + path.sep) && filePath !== baseDir) {
    res.writeHead(403);
    res.end('Forbidden');
    return;
  }

  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404);
      res.end('Not found');
      return;
    }
    const ext = path.extname(filePath).toLowerCase();
    res.writeHead(200, { 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream' });
    res.end(data);
  });
}

module.exports = { startServer };
