import puppeteer from "puppeteer-core";
import { mkdirSync } from "fs";

const OUT = "/home/devuser/work/screenshots";
mkdirSync(OUT, { recursive: true });

const browser = await puppeteer.launch({
  executablePath: "/usr/bin/chromium",
  headless: "new",
  args: [
    "--no-sandbox",
    "--disable-gpu",
    "--window-size=1440,900",
    "--use-gl=angle",
    "--use-angle=swiftshader",
    "--autoplay-policy=no-user-gesture-required",
  ],
  defaultViewport: { width: 1440, height: 900, deviceScaleFactor: 1 },
});

const page = await browser.newPage();
page.on("console", (m) => console.log("PAGE", m.text()));
page.on("pageerror", (e) => console.log("ERR", e.message));

async function shot(name) {
  await page.screenshot({ path: `${OUT}/${name}`, type: "png" });
  console.log("saved", name);
}

await page.goto("http://127.0.0.1:5173/?level=1", {
  waitUntil: "networkidle0",
  timeout: 30000,
});
await page.waitForFunction(() => window.__lumina && window.__lumina.game && window.__lumina.renderer?.layout, {
  timeout: 15000,
});

const info = await page.evaluate(() => {
  const { game } = window.__lumina;
  game.delayLeft = 40;
  game.min = 8;
  const seq = [
    [3, 2, "h"],
    [3, 3, "h"],
    [3, 4, "cross"],
    [3, 5, "sw"],
    [4, 5, "v"],
    [5, 5, "se"],
    [5, 6, "h"],
    [5, 7, "nw"],
    [4, 7, "v"],
    [3, 7, "sw"],
    [3, 6, "h"],
    [4, 4, "v"],
    [5, 4, "ne"],
    [2, 4, "v"],
    [1, 4, "se"],
    [1, 5, "h"],
    [1, 6, "sw"],
    [2, 6, "ne"],
    [2, 7, "h"],
  ];
  for (const [r, c, p] of seq) {
    game.queue[0] = p;
    game.place(r, c);
  }
  game.queue = ["ne", "cross", "res_h", "ow_e", "sw"];
  game.cell(3, 4).bonus = true;
  return {
    phase: game.phase,
    delay: game.delayLeft,
    placed: seq.length,
    start: game.spec.start,
  };
});
console.log(info);
await new Promise((r) => setTimeout(r, 250));
await shot("04-play.png");

await page.evaluate(() => {
  const { game } = window.__lumina;
  game.delayLeft = 0.05;
});
await new Promise((r) => setTimeout(r, 2200));
await shot("05-flow.png");

await page.goto("http://127.0.0.1:5173/", { waitUntil: "networkidle0" });
await page.click("#sc-boot");
await new Promise((r) => setTimeout(r, 400));
await page.click('[data-act="help"]');
await new Promise((r) => setTimeout(r, 300));
await shot("07-help.png");

await page.click('[data-act="menu"]');
await new Promise((r) => setTimeout(r, 200));
await page.click('[data-act="settings"]');
await new Promise((r) => setTimeout(r, 300));
await shot("08-settings.png");

await browser.close();
console.log("done");
