import { execFile } from "node:child_process";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);
const baseUrl = process.env.UFORIA_BASE_URL ?? "https://uforia.polynomial.fi";
const resolveIp = process.env.UFORIA_RESOLVE_IP;
const resolvedBaseUrl = new URL(baseUrl);

async function fetchJson(path) {
  const url = new URL(path, baseUrl);
  if (!resolveIp) {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`${path} failed with ${response.status}`);
    }
    return response.json();
  }

  const port = resolvedBaseUrl.port || (resolvedBaseUrl.protocol === "https:" ? "443" : "80");
  const { stdout } = await execFileAsync("curl", [
    "--fail",
    "--silent",
    "--show-error",
    "--resolve",
    `${resolvedBaseUrl.hostname}:${port}:${resolveIp}`,
    url.toString(),
  ]);
  if (!stdout) {
    throw new Error(`${path} returned an empty response`);
  }
  return JSON.parse(stdout);
}

const healthJson = await fetchJson("/proxy/system/health");
const dashboardsJson = await fetchJson("/proxy/options/dashboards");
if (!healthJson || !dashboardsJson) {
  throw new Error("Smoke responses were empty");
}

const { chromium } = await import("playwright");
const launchOptions = { headless: true };
if (resolveIp) {
  launchOptions.args = [
    `--host-resolver-rules=MAP ${resolvedBaseUrl.hostname} ${resolveIp}`,
  ];
}
const browser = await chromium.launch(launchOptions);
const page = await browser.newPage();
await page.goto(new URL("/options", baseUrl).toString(), {
  waitUntil: "domcontentloaded",
});
await page.waitForSelector("text=Options analytics workbench", { timeout: 60000 });
await browser.close();
