const { app, BrowserWindow } = require("electron");
const { resolve } = require("node:path");
const { writeFile } = require("node:fs/promises");

const output = resolve(process.argv.at(-1)?.endsWith(".png") ? process.argv.at(-1) : "launcher-settings-preview.png");
const page = /^[a-z-]+$/.test(process.env.BGLANDS_CAPTURE_PAGE || "") ? process.env.BGLANDS_CAPTURE_PAGE : "home";
const width = Number(process.env.BGLANDS_CAPTURE_WIDTH || 1180);
const height = Number(process.env.BGLANDS_CAPTURE_HEIGHT || 760);
app.commandLine.appendSwitch("disable-gpu");
app.commandLine.appendSwitch("disable-dev-shm-usage");

app.whenReady().then(async () => {
  const window = new BrowserWindow({ width, height, show: false, webPreferences: { sandbox: true } });
  await window.loadFile(resolve(__dirname, "../dist/renderer/index.html"), { hash: page });
  await new Promise((resolveDelay) => setTimeout(resolveDelay, 3_000));
  const image = await window.webContents.capturePage();
  await writeFile(output, image.toPNG());
  await window.close();
  app.quit();
}).catch((error) => {
  process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`);
  app.exit(1);
});
