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

process.env.NODE_ENV = "production";

// Load .env when present (cPanel Setup Node.js App may already inject vars).
try {
  require("dotenv").config({ path: path.join(__dirname, ".env") });
} catch {
  // dotenv is optional at runtime if env vars come from the panel.
}

const buildIdPath = path.join(__dirname, ".next", "BUILD_ID");
if (!fs.existsSync(buildIdPath)) {
  console.error(
    "Missing production build (.next/BUILD_ID).\n\n" +
      "On shared hosting, build on your computer then upload the .next folder:\n" +
      "  npm install\n" +
      "  npm run build\n\n" +
      "Upload .next/ to the server, then restart the Node.js app.\n" +
      "Do NOT run 'npm run dev' on cPanel — it will run out of memory.",
  );
  process.exit(1);
}

// Ensure default writable directories exist before Next starts.
const dataDir = path.join(__dirname, "data");
const uploadsDir = process.env.UPLOAD_DIR
  ? path.resolve(process.env.UPLOAD_DIR)
  : path.join(dataDir, "uploads");

try {
  fs.mkdirSync(dataDir, { recursive: true });
  fs.mkdirSync(uploadsDir, { recursive: true });
} catch (error) {
  console.error("Could not create data/upload directories:", error);
  process.exit(1);
}

const port = String(process.env.PORT || process.env.IPORT || "3000");

process.argv = [
  process.argv[0],
  process.argv[1],
  "start",
  "-p",
  port,
  "-H",
  "0.0.0.0",
];

require("next/dist/bin/next");
