import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { existsSync, readFileSync } from "node:fs";

function loadEnvFile(file = ".env") {
  if (!existsSync(file)) return;

  readFileSync(file, "utf8").split(/\r?\n/).forEach((line) => {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) return;

    const separatorIndex = trimmed.indexOf("=");
    if (separatorIndex < 1) return;

    const key = trimmed.slice(0, separatorIndex).trim();
    const value = trimmed.slice(separatorIndex + 1).trim().replace(/^["']|["']$/g, "");
    if (!process.env[key]) process.env[key] = value;
  });
}

loadEnvFile();

export default defineConfig({
  root: "website",
  publicDir: "public",
  plugins: [react()],
  server: {
    host: "0.0.0.0",
    port: Number(process.env.PORT || 5173)
  },
  preview: {
    host: "0.0.0.0",
    port: Number(process.env.PORT || 4173)
  },
  build: {
    outDir: "dist",
    emptyOutDir: true
  }
});
