const fs = require("node:fs");
const path = require("node:path");

function wireBundledBinary(binaryName, envVariable) {
  if (process.env[envVariable]) {
    return;
  }

  const extension = process.platform === "win32" ? ".exe" : "";
  const candidatePath = path.join(__dirname, ".next", "standalone", "bin", process.platform, `${binaryName}${extension}`);
  if (!fs.existsSync(candidatePath)) {
    return;
  }

  if (process.platform !== "win32") {
    try {
      fs.chmodSync(candidatePath, 0o755);
    } catch {
      // Best effort only; host may still allow execution with existing perms.
    }
  }

  process.env[envVariable] = candidatePath;
}

wireBundledBinary("ffmpeg", "FFMPEG_PATH");
wireBundledBinary("ffprobe", "FFPROBE_PATH");
wireBundledBinary("yt-dlp", "YT_DLP_PATH");

require("./.next/standalone/server.js");
