#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import fs from "node:fs";

function command(label, cmd, args = ["--version"], required = true) {
  const result = spawnSync(cmd, args, {encoding: "utf8"});
  return {label, required, ok: result.status === 0, detail: (result.stdout || result.stderr || "not found").trim().split("\n")[0]};
}

function pythonImport(label, moduleName, required) {
  return command(label, "python3", ["-c", `import ${moduleName}; print(${moduleName}.__version__ if hasattr(${moduleName}, '__version__') else 'available')`], required);
}

const browserCandidates = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/usr/bin/google-chrome", "/usr/bin/chromium"];
const browser = browserCandidates.find(fs.existsSync);
const checks = [
  command("Node.js", process.execPath, ["--version"], true),
  command("Python", "python3", ["--version"], true),
  {label: "Chrome/Chromium", required: true, ok: Boolean(browser), detail: browser || "not found; install Chrome or Chromium"},
  pythonImport("Playwright", "playwright", true),
  pythonImport("Pillow", "PIL", true),
  pythonImport("PyMuPDF", "fitz", false)
];
console.log(JSON.stringify({ok: checks.every(item => item.ok || !item.required), checks}, null, 2));
process.exitCode = checks.every(item => item.ok || !item.required) ? 0 : 1;
