#!/usr/bin/env node
/**
 * Maakt een screenshot van een tool-website voor gebruik in een review.
 *
 * Gebruik:
 *   npm run screenshot -- <url> <slug> [--full-page]
 *
 * Voorbeeld:
 *   npm run screenshot -- https://watermelon.ai watermelon
 *
 * Zet het resultaat in src/assets/reviews/<slug>/screenshot.png
 */
import { chromium } from "playwright";
import { mkdir } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(__dirname, "..");

const args = process.argv.slice(2);
const fullPage = args.includes("--full-page");
const positional = args.filter((a) => !a.startsWith("--"));
const [url, slug] = positional;

if (!url || !slug) {
  console.error("Gebruik: npm run screenshot -- <url> <slug> [--full-page]");
  process.exit(1);
}

const outDir = path.join(projectRoot, "src", "assets", "reviews", slug);
const outFile = path.join(outDir, "screenshot.png");

await mkdir(outDir, { recursive: true });

const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });

try {
  await page.goto(url, { waitUntil: "networkidle", timeout: 30_000 });
} catch {
  // sommige sites (chat-widgets, analytics) worden nooit helemaal "idle" —
  // val dan terug op gewoon "load" zodat de screenshot toch doorgaat
  await page.goto(url, { waitUntil: "load", timeout: 30_000 });
}

await page.screenshot({ path: outFile, fullPage });
await browser.close();

console.log(`Screenshot opgeslagen: ${path.relative(projectRoot, outFile)}`);
