const { exec } = require("child_process");
const path = require("path");
const fs = require("fs");
const Tesseract = require("tesseract.js"); // Add this

async function extractTextFromImage(imagePath) {
  const result = await Tesseract.recognize(imagePath, 'eng', { logger: () => {} });
  return result.data.text;
}

async function convertWithPoppler(pdfPath, outputDir) {
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const outputPrefix = path.join(outputDir, "slide");

  return new Promise((resolve, reject) => {
    const command = `pdftoppm -jpeg -r 150 "${pdfPath}" "${outputPrefix}"`;
    console.log("Converting PDF:", pdfPath);

    exec(command, async (error, stdout, stderr) => {
      if (error) {
        console.error("Poppler error:", stderr);
        return reject(new Error("PDF to image conversion failed."));
      }

      const files = fs.readdirSync(outputDir)
        .filter(f => f.startsWith("slide") && f.endsWith(".jpg"))
        .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));

      const slideData = [];

      for (let index = 0; index < files.length; index++) {
        const oldFile = files[index];
        const oldPath = path.join(outputDir, oldFile);

        // OCR: Extract text
        const text = await extractTextFromImage(oldPath);
        const isQuiz = text.trim().toLowerCase().startsWith("quiz");

        // Rename with quiz suffix if needed
        const newFileName = `slide${index + 1}${isQuiz ? "_quiz" : ""}.jpg`;
        const newPath = path.join(outputDir, newFileName);
        fs.renameSync(oldPath, newPath);

        slideData.push({
          slideNumber: index + 1,
          imageUrl: `/slides/${newFileName}`,
        });
      }

      if (slideData.length === 0) {
        return reject(new Error("No slides generated."));
      }

      resolve(slideData);
    });
  });
}

module.exports = { convertWithPoppler };
