#!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

function fail(message, details) {
  const payload = { error: message };
  if (details) payload.details = details;
  process.stderr.write(`${JSON.stringify(payload)}\n`);
  process.exit(1);
}

async function main() {
  try {
    await import("cloakbrowser");
    await import("playwright-core");
  } catch (error) {
    fail(
      "Missing dependency/config: web-automation requires cloakbrowser and playwright-core.",
      error instanceof Error ? error.message : String(error)
    );
  }

  const browsePath = path.join(__dirname, "browse.ts");
  const browseSource = fs.readFileSync(browsePath, "utf8");
  if (!/launchPersistentContext/.test(browseSource) || !/from ['"]cloakbrowser['"]/.test(browseSource)) {
    fail("browse.ts is not configured for CloakBrowser.");
  }

  process.stdout.write("OK: cloakbrowser + playwright-core installed\n");
  process.stdout.write("OK: CloakBrowser integration detected in browse.ts\n");
}

main().catch((error) => {
  fail("Install check failed.", error instanceof Error ? error.message : String(error));
});
