const { app, BrowserWindow } = require("electron");
const fs = require("fs");
const path = require("path");

const ROOT = path.resolve(__dirname, "..");
const inputArg = process.argv[2];
const outputArg = process.argv[3];

if (!inputArg || !outputArg) {
  console.error("Usage: electron scripts/export_guide_pdf.js <input.html> <output.pdf>");
  process.exit(1);
}

const htmlPath = path.isAbsolute(inputArg) ? inputArg : path.join(ROOT, inputArg);
const pdfPath = path.isAbsolute(outputArg) ? outputArg : path.join(ROOT, outputArg);

async function run() {
  const win = new BrowserWindow({
    width: 1400,
    height: 1900,
    show: false,
    backgroundColor: "#ffffff",
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
    },
  });

  await win.loadFile(htmlPath);
  await new Promise((resolve) => setTimeout(resolve, 1200));

  const pdfData = await win.webContents.printToPDF({
    printBackground: true,
    pageSize: "A4",
    margins: { top: 0.4, bottom: 0.4, left: 0.35, right: 0.35 },
    landscape: false,
    preferCSSPageSize: true,
  });

  fs.writeFileSync(pdfPath, pdfData);
  await win.close();
  console.log(`PDF generated: ${pdfPath}`);
}

app.whenReady()
  .then(run)
  .then(() => app.quit())
  .catch((error) => {
    console.error(error);
    app.quit();
    process.exit(1);
  });
