#!/usr/bin/env node

var version = process.version;
var [majorVersion] = version.replace("v", "").split(".");
if (Number(majorVersion) < 20) {
  console.error(
    "Builder.io Dev Tools requires Node.js 20 or higher. You are currently running Node.js " +
      version +
      ".\nPlease upgrade to Node.js 20 or higher: https://nodejs.org/",
  );
  process.exit(1);
}

// Filter out any PATH entries that contain "builder-electron-node-bin"
// This prevents fake node paths from the CLI caller from being passed through
if (process.env.PATH) {
  const pathSeparator = process.platform === "win32" ? ";" : ":";
  const pathEntries = process.env.PATH.split(pathSeparator);
  const filteredPaths = pathEntries.filter(
    (pathEntry) => !pathEntry.includes("builder-electron-node-bin"),
  );
  process.env.PATH = filteredPaths.join(pathSeparator);
}

// Ensure File global is available for undici compatibility
// This is needed when running via npx with local paths where dependencies
// might resolve from parent node_modules with different undici versions
// undici v7+ requires File to be available, and it checks for it at module load time
if (typeof globalThis.File === "undefined") {
  try {
    // In Node.js 20+, File is available from node:buffer
    const { File } = require("node:buffer");
    globalThis.File = File;
  } catch (e) {
    console.error("Error importing File from node:buffer", e);
    // Fallback: create a minimal File polyfill for undici compatibility
    // This is a basic implementation that should satisfy undici's type checks
    globalThis.File = class File extends Blob {
      constructor(chunks, name, options) {
        super(chunks, options);
        this.name = name || "";
        this.lastModified = options?.lastModified || Date.now();
      }
    };
  }
} else {
  // Ensure File is explicitly set in globalThis even if it already exists
  // This helps with module resolution timing issues when using npx with local paths
  try {
    const { File } = require("node:buffer");
    globalThis.File = File;
  } catch (e) {
    console.error("Error importing File from node:buffer", e);
    // If we can't import it, the existing global File should be sufficient
  }
}

require("./index.cjs");
